c++ - 如何在模板中转发左右值引用
问题描述
我对在模板中转发 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;
}
error: cannot bind non-const lvalue reference of type ‘std::basic_string<char>&’ to an rvalue of type ‘std::basic_string<char>’
我也尝试过std::forward(args...)
,因为 C++17 可以自动获取模板类型。也没有用(不适合std::forward
?)。
那么如何在一个模板函数中同时转发左右值引用呢?提前致谢。
解决方案
str2
是一个字符数组而不是 a std::string
,编译器正在尝试std::string
从您的字符数组创建一个临时值,但是由于fn2
采用了非常量引用,所以不能使用临时值。
如果您更改str2
为 astd:: string
它可能会编译。
推荐阅读
- laravel - 克隆 laravel 到 centos7 时的问题
- c++ - 映射运算符 [] 在 while 循环中不起作用(预期的主表达式)
- c++ - 如何在 OpenGL 中仅为一个对象设置材质?
- android - 检测页面结尾并禁用 AndroidPdfViewer 中的滚动
- c# - 使用实体框架的表中的相关数据
- spring - ActiveMQ messageId 无法停止复制
- javascript - 以特殊字符开头的模式的 JavaScript 正则表达式
- python - Numpy 中的高效矩阵索引
- javascript - 如何使用Vue js删除和编辑firebase中的记录
- python-3.x - Dask分布式库给出序列化错误