mercredi 25 novembre 2020

How to detect universal reference parameter type with std::is_same

Have a look at these lines:

template <typename T>
void f(T&& param) {
    if (std::is_same<T, int>::value) {
        cout << "param is an int" << endl;
    } else {
        cout << "param is not an int" << endl;
    }
    if (std::is_same<T, int&>::value) {
        cout << "param is an lvalue reference to int" << endl;
    }
    if (std::is_same<T, int&&>::value) {
        cout << "param is an rvalue reference to int" << endl;
    }
}
int main() {
    int i = 0;
    f(i);
    f(std::move(i));
    return 0;
}

The first function call f(i) yields:

param is not an int

param is an lvalue reference to int

which is what I expected, because as per the template argument deduction rules, T resolves to T&, resulting in T&& & which yields T& because of reference collapsing.

The second funtion call f(std::move(i)) yields

param is an int

which is not what I expected. I'd have expected

param is an rvalue reference to int

or at least

param is not an int

Can someone explain why my expectations regarding the second function call are not met ?

Aucun commentaire:

Enregistrer un commentaire