C++ 如何转发模板中的左右值引用
我对在模板中转发宇宙引用感到困惑。我的代码如下:C++ 如何转发模板中的左右值引用,c++,c++17,C++,C++17,我对在模板中转发宇宙引用感到困惑。我的代码如下: class A { public: void fn(std::unique_ptr<std::string> n) { (*n) += "1"; cout << "n: " << *n << endl; } void fn2(std::string& n) { n += "2";
class A {
public:
void fn(std::unique_ptr<std::string> n) {
(*n) += "1";
cout << "n: " << *n << endl;
}
void fn2(std::string& n) {
n += "2";
cout << "n: " << n << endl;
}
};
template <typename Func, typename Class, typename... Args>
std::thread create_thread(Func&& func, Class* this_ptr, Args&&... args) {
auto handler = [&] {
(this_ptr->*func)(std::forward<Args>(args)...); // error
};
return std::thread(handler);
}
int main() {
auto str1 = std::make_unique<std::string>("a");
auto str2 = "b";
A a;
auto t1 = create_thread(&A::fn, &a, std::move(str1));
auto t2 = create_thread(&A::fn2, &a, std::ref(str2));
t1.join();
t2.join();
return 0;
}
A类{
公众:
无效fn(标准::唯一性\u ptr n){
(*n)+=“1”;
coutstr2
是字符数组而不是std::string
,编译器试图从字符数组创建一个临时std::string
,但由于fn2
采用非常量引用,因此无法使用临时值
如果将str2
更改为std::string
,它可能会编译。旁注:在对象上创建调用成员函数的线程不需要lambda,std::thread
可以直接处理,因此您的函数看起来就像{return std::thread(func,this\ptr,args…)
–您会注意到函数调用本身与直接创建线程没有任何区别:std::thread t1(&A::fn,&A,std::move(str1))
,因此您可能会问自己是否需要该函数。。。
error: cannot bind non-const lvalue reference of type ‘std::basic_string<char>&’ to an rvalue of type ‘std::basic_string<char>’