这个问题涉及
this
,
this
而且可能
this
.
我有以下课程,其中
AddFunction
方法接收一个函数和该函数的参数列表,然后生成一个
std::thread
使用传递的参数调用传递的函数:
class Processes {
public:
Processes() {}
~Processes() {
for (auto &t : threads_) {
t.join();
}
}
template <class Function, typename... Args>
void AddFunction(Function &&func, Args &&... args) {
threads_.emplace_back(std::forward<Function>(func),
std::forward<Args>(args)...);
}
private:
std::vector<std::thread> threads_;
}
这将导致每个参数都有一个副本,如果对象不可复制,编译将失败,因为
标准::螺纹
需要包装引用
std::ref
为了保证此对象将超过线程的生存期,否则将复制它。
当在目标函数签名中指定时
.
我试着使用lambda:
template <class Function, typename... Args>
void AddFunction(Function &&func, Args &&... args) {
threads_.emplace_back([&]() { func(std::forward<Args>(args)...); });
}
但这会导致不正确的行为,因为lambda在按值传递值之前通过引用捕获值,从而导致按引用捕获行为。
如何实现将参数作为值或引用转发的函数
根据目标函数签名
?
例子:
void Foo(int a, std::vector<int> const &b) { /* ... */ }
int main() {
Processes procs;
int a = 6;
std::vector<int> b;
procs.AddFunction(
Foo,
a, // Should be passed by value
b // Should be passed by reference (as implemented by std::ref)
);
return 0;
}