首页 > 解决方案 > 在这种情况下如何正确使用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;
};

并像这样使用它:

int task_with_argument(int value)
{
 return value;
}

addTask( task_with_argument, 10 );

我收到错误:

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

我也试过这个:

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

再次错误:

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

哪里有问题?

标签: c++

解决方案


这个电话:

std::forward(arguments...)

不是正确的使用方法std::forward

相反,您应该将函数的参数作为转发引用:

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

然后使用这样的参数:

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

推荐阅读