我对在模板中转发 Universe 引用感到困惑。我的代码如下:
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;
}
Run Code Online (Sandbox Code Playgroud)
error: cannot bind non-const lvalue reference of type ‘std::basic_string<char>&’ to an rvalue of type ‘std::basic_string<char>’
Run Code Online (Sandbox Code Playgroud)
我也尝试过,std::forward(args...)因为 C++17 可以自动获取模板类型。也没有用(不适合std::forward?)。
那么如何在一个模板函数中同时转发左右值引用呢?提前致谢。
str2是字符数组而不是std::string,编译器试图std::string从您的字符数组创建一个临时值,但由于fn2采用非常量引用,因此无法使用临时值。
如果您更改str2为 astd:: string它可能会编译。