简体   繁体   English

在这种情况下如何正确使用 std forward

[英]how to use std forward correctly in this case

Here is a class which has queue as private member and addTask() method and when i compile this i have error with std::forward:这是一个将队列作为私有成员和 addTask() 方法的类,当我编译它时,我遇到 std::forward 错误:

#include <iostream>
#include <unistd.h>

#include <functional>
#include <vector>
#include <thread>
#include <condition_variable>
#include <queue>
#include <future>
#include <memory>
#include <utility>

class Pool {
    public:
        using Task = std::function<void()>;

        Pool(){}
        ~Pool(){}

        template<typename Func, typename ...Args>
        auto addTask(Func task, Args &&... arguments) -> std::future<decltype(task(arguments...))>
        {
            auto wrapper = std::make_shared<std::packaged_task<decltype(task(arguments...)) (Args...)>>(std::move(task));
            {
                std::unique_lock<std::mutex> lock(mEventMutex);
                mTasks.emplace([=] {
                    (*wrapper)(std::forward<Args...>(arguments...));
                });
            }
            return wrapper->get_future();         
        }

    private:
        std::queue<Task> mTasks;
        std::mutex mEventMutex;
};

and using it like this:并像这样使用它:

int task_with_argument(int value)
{
 return value;
}

addTask( task_with_argument, 10 );

and i am getting error:我收到错误:

error: no matching function for call to ‘forward(const int&)’

I've also tried this:我也试过这个:

(*wrapper)(std::forward<Agrs>(arguments)...);

and again error:再次错误:

error: binding reference of type ‘std::remove_reference<int>::type&’ {aka ‘int&’} to ‘const int’ discards qualifiers

Where is a problem?哪里有问题?

This call:这个电话:

std::forward(arguments...)

is not the correct way to use std::forward .不是使用std::forward的正确方法。

Instead, you should take the arguments to the function as forwarding references:相反,您应该将函数的参数作为转发引用:

addTask(Func task, Args &&... arguments)

and then use the arguments like this:然后使用这样的参数:

std::forward<Args...>(arguments...)

You attempt to apply perfect forwarding, but this does not make sense in your problem solution.您尝试应用完美转发,但这在您的问题解决方案中没有意义。 To stow away a task and all its arguments, copies of the arguments have to be made.要隐藏任务及其所有参数,必须制作参数的副本。 This defeats all perfect forwarding attempts.这击败了所有完美的转发尝试。

Furthermore, you ask your std::future to store a decltype(task(arguments...) , ie to pick an overload that is invoked without perfectly forwarded arguments. It is inconsistent, to say the least, to do the actual call with perfectly forwarded arguments (if that would have made sense).此外,您要求std::future存储一个decltype(task(arguments...) ,即选择一个在没有完美转发参数的情况下调用的重载。至少可以说,使用以下方法进行实际调用是不一致的完美转发的论点(如果这有意义的话)。

Just remove std::forward :只需删除std::forward

mTasks.emplace([=] { (*wrapper)(arguments...); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM