c++ - 在这种情况下如何正确使用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
哪里有问题?
解决方案
这个电话:
std::forward(arguments...)
不是正确的使用方法std::forward
。
相反,您应该将函数的参数作为转发引用:
addTask(Func task, Args &&... arguments)
然后使用这样的参数:
std::forward<Args...>(arguments...)
推荐阅读
- tensorflow - 如何使用 TFRecordWriter 编写 tf.Data.dataset.take() 的结果?
- ruby - 是否可以将 ruby 哈希从一个文件读入另一个文件,然后使用它的值?
- node.js - 将 MERN 应用程序部署到 Heroku 时出错(前端部署成功,但后端没有部署)
- java - JTable 中使用 Search Filter 和 mouseClicked 事件时的问题
- mongodb - 如何通过计数MongoDB在数组对象组中设置限制
- ansible-tower - 使用 python 从 ansible 塔获取 OAuth2 令牌?
- go - 使用 Go/SQLX 找不到存在的 Struct 属性
- django - 我应该什么时候在 Django Rest Framework 序列化程序中使用 ParseError 和 ValidationError?
- clojure - Clojure寻找矩形区域
- ios - UICollectionViewCell 在滚动开始后立即更改数据