Template argument deduction
lastmod 2020-01-31created 2019-10-093 edits
In order to instantiate a function template, every template argument must be known, but not every template argument has to be specified. When possible, the compiler will deduce the missing template arguments from the function arguments. This occurs when a function call is attempted, when an address of a function template is taken, and in some other contexts.
Template specialization and deduction order
#include <iostream>
template <class T>
void f( T )
{
std::cout << "template <class T> void f( T )\n" ;
}
template <>
void f<int*>( int * )
{
std::cout << "template <> void f<int*>( int * )\n" ;
}
template <class T>
void f( T* )
{
std::cout << "template <class T> void f( T* )\n" ;
}
// ...
int main( void )
{
int *p;
f( p ); // 어떤 f가 호출 될까?
return 0;
}
You need to know "how does a function template get called?"
- If there is a plain non-template function, it is always called first.
- If 1 does not apply, look for a "base template function".
- If a "base template function" is found by 2, check whether a specialized version matches; if there is one, the specialization is called first. If not, the "concrete base template function" matching the template parameters is instantiated and called. If there are multiple "concrete base template functions" or none, it spits out a compile-time error.
Result output: