【发布时间】:2014-11-19 23:29:24
【问题描述】:
我正在尝试制作一种 std::thread 形式,它在线程中执行的代码周围放置一个包装器。不幸的是,由于我对右值和我试图传递的 Function 模板类型的理解很差,我无法编译它。这是我的代码:
#include <vector>
#include <thread>
#include <utility>
void Simple2(int a, int b) {}
template <typename Function, typename... Args>
void Wrapper(Function&& f, Args&&... a) {
f(std::forward<Args>(a)...);
}
class Pool {
public:
template <typename Function, typename... Args>
void Binder(Function&& f, Args&&... a) {
std::thread t(Wrapper<Function, Args...>,
std::forward<Function>(f), std::forward<Args>(a)...);
}
};
int main() {
Wrapper(Simple2, 3, 4); // Works
Pool pool;
pool.Binder(Simple2, 3, 4); // Doesn't compile
}
这里看起来很重要的 Clang3.0 输出是:
/usr/include/c++/4.6/functional:1286:9: error: non-const lvalue reference to type 'void (int, int)' cannot bind to a value of unrelated type 'void (*)(int, int)'
和
note: in instantiation of function template specialization 'std::thread::thread<void (void (&)(int, int), int &&, int &&), void (&)(int, int), int, int>' requested here
我认为这暗示了 Wrapper<Function, Args...> 和给予 std::thread 的右值 f, a... 之间的不匹配。
如果我将 std::forward<Function>(f) 更改为 std::ref(f),这会在 GCC4.9 和更新的 Clang 中编译。
【问题讨论】:
标签: c++ c++11 rvalue-reference stdthread perfect-forwarding