Invalid initialization of non-const reference of type

后端 未结 3 1992
深忆病人
深忆病人 2021-01-01 17:49

In the following code, I\'m not able to pass a temporary object as argument to the printAge function:

struct Person {
  int age;
  Person(int _a         


        
3条回答
  •  长情又很酷
    2021-01-01 17:57

    Or, if you have a C++11-compliant compiler, can use the so called universal reference approach, which, via reference collapsing rules, can bind to both lvalue and rvalue references:

    #include 
    using namespace std;
    
    struct Person {
      int age;
      Person(int _age): age(_age) {}
    };
    
    template // can bind to both lvalue AND rvalue references
    void printAge(T&& person) {
       cout << "Age: " << person.age << endl;
    }
    
    int main () {
      Person p(50);
      printAge(Person(50));  // works now
      printAge(p);
      return 0;
    }
    

    Or, in C++14,

    void printAge(auto&& person) {
       cout << "Age: " << person.age << endl;
    }
    

提交回复
热议问题