lundi 8 octobre 2018

Template allows lvalue to become bound with rvalue reference

This program:

using namespace std;
#include <iostream>
#include <memory>

struct Dog 
{ 
    int legs; 
} adog;

Dog gimmeadog() { return adog; }

void walk(Dog && d) { cout << "Nonconst right dog walk\n"; }

//template<class T> void walk(T && d) { d.legs=3; cout << "Nonconst right something walk\n"; }

int main() {
    Dog mydog = gimmeadog();
    walk(mydog);    
    return 0;
}

correctly fails to compile on gcc because:

error: cannot bind rvalue reference of type ‘Dog&&’ to lvalue of type ‘Dog’
  walk(mydog);

but if you un-comment the template it happily binds and prints "Nonconst right something walk".

Why? What type is T taking when it works? Is this not defeating the object of rvalue references?

Aucun commentaire:

Enregistrer un commentaire