edA-qa mort-ora-y
edA-qa mort-ora-y

Reputation: 31901

typeid of template parameter universal reference

Is there some way I can output if the template parameter is an rvalue reference, reference, or constant value? That is, I'm using a universal reference and would, for debugging/learning purposes, like to see exactly which type actually matched.

template<typename T>
void write( T && f ) {
    std::cout << typeid(f).name;
}

This of course doesn't show me that it was an rvalue, lvalue, or const parameter which was passed. I would like somehow to display which parameter type was actually matched. Note that I'm specifically interested in seeing how this single function is matched.

Upvotes: 1

Views: 984

Answers (1)

Grizzly
Grizzly

Reputation: 20191

You might want to look into the type_traits header. It has traits for detecting if a type is const and if it is an reference. You can check T to see what kind of reference you have bound:

  1. If f is of laval-reference-type, then so is T
  2. If f is const then so is T
  3. If f is an rvalue-reference, then T is not an reference (if bound by argument deduction at least).

So you could do something like this:

template<typename T>
void write( T && f ) {
    std::cout << "f is a " <<(std::is_const<typename std::remove_reference<T>::type>::value?"const ":"")<<(std::is_lvalue_reference<T>::value?"lvalue":"rvalue")<<" reference";
}

Upvotes: 3

Related Questions