Template argument deduction
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.
템플릿 특수화 및 추론 순서
#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;
}
"함수 템플릿이 어떻게 호출 될까?"를 알아야 할 것이다.
- 템플릿이 아닌 일반 함수가 있다면, 무조건 그것이 1등으로 호출 한다.
- 1번이 안된다면, "기본 템플릿 함수"을 찾는다.
- 2번에 의해 찾은 "기본 템플릿 함수"가 있다면, 특수화버전과 맞는지 찾으며, 있다면 특수화를 우선적으로 호출, 없다면, 템플릿 매개변수에 맞는 "구체적인 기본 템플릿 함수"를 인스턴스화 하여, 호출한다. 만약 "구체적인 기본 템플릿 함수"가 여러개이거나 없다면, 컴파일 타임 에러를 벹어 낸다.
Result output: