Search code examples
c++forwarding-reference

Error: Using std::forward in initialize-lists


I create a class:

#include <iostream>
#include <string>

class Person {
 public:
  template<typename T>
  Person(T&& _name) :
    m_name(std::forward<T>(_name)) {
    }
 private:
  std::string m_name;
};

and invoke it:

int main(int argc, char const *argv[]) {
  Person p("Nancy");
  return 0;
}

But the compiler throw a error and lots of message:

t.cc:8:5: error: no matching constructor for initialization of 'std::string' (aka 'basic_string<char, char_traits<char>, allocator<char> >')
    m_name(std::forward<T>(_name)) {
    ^      ~~~~~~~~~~~~~~~~~~~~~~
1 error generated.

Type of _name is universal reference, and I perfectly forward _name to m_name.

As I know,

if _name is l-value, type of _name will be inferred as std::string&,

if _name is r-value, type of _name will be inferred asstd::string&&,

I initialize Person with "Nancy" which is r-value, so it should work fine as I known.

I feel confused.


Solution

  • std::forward function is defined in utility header so you are missing your include statement:

    #include <utility>
    

    Check the reference.