Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/160.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何转发模板中的左右值引用_C++_C++17 - Fatal编程技术网

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”;

cout
str2
是字符数组而不是
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>’