首页 > 解决方案 > 如何在模板中转发左右值引用

问题描述

我对在模板中转发 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?)。

那么如何在一个模板函数中同时转发左右值引用呢?提前致谢。

标签: c++c++17

解决方案


str2是一个字符数组而不是 a std::string,编译器正在尝试std::string从您的字符数组创建一个临时值,但是由于fn2采用了非常量引用,所以不能使用临时值。

如果您更改str2为 astd:: string它可能会编译。


推荐阅读