Search code examples
c++templatesconstantstemplate-argument-deduction

Explanation of the C++ template function argument deduction when matching `T const &&t` against `int const *`


I don't understand how the argument deduction rule works in this case. I have the following simple code snippet:

template<typename T>
void fn(T const &&t) {
   std::cout << __PRETTY_FUNCTION__  << std::endl;
   std::cout << typeid(decltype(t)).name() << std::endl;
}
int main() {
   int const *ar = nullptr;
   std::cout << typeid(ar).name() << std::endl;
   fn(std::move(ar));
}

The result I get is as follows:

PKi
void fn(const T &&) [T = const int *]
PKi

What I don't understand is why T is inferred as const int *. Why the const did not get pattern matched?


Solution

  • In the parameter declaration T const &&t, const is qualified on T, i.e. t is declared as an rvalue-reference to const T.

    When ar with type const int * is passed, T is deduced as const int *, then the type of t would be const int * const &&, i.e. an rvalue-reference to const pointer to const int. Note that the consts are qualified on different things (on different levels), one for the pointer, one for the pointee.