相关概念:
#include <iostream>
using namespace std;
//通用模板
template <typename T>
void func1(T a, T b) {
cout << a << " " << b << endl;
}
//显示具体化(explicit specialization)
//指出当参数为int时通过此函数而不是通用模板生成实例
template <>
void func1<int>(int a, int b) {
cout << "func1" << endl;
}
//实例化在生成的可执行文件中生成真正的指令
template void func1<char>(char, char); //显式实例化(explicit instantiation)
int main() {
double x = 1.0, y = 1.0;
func1(x, y); //隐式实例化
func1<string>("a", "b"); //显式实例化
return 1;
}
显式具体化可以为某种类型的参数定义不同于通用模板的实现,匹配时显式实例化的模板优先于通用模板。但也可以为特定的函数类型定义非模板函数,匹配时非模板函数优先于模板函数,比如:
#include <iostream>
using namespace std;
template <typename T>
void func1(T a, T b) {
cout << a << " " << b << endl;
}
template <>
void func1<int>(int a, int b) {
cout << "func1" << endl;
}
void func1(int a, int b) {
cout << "another func1";
}
int main() {
int x = 0, y = 0;
func1(x, y); //another func1
return 1;
那为什么还需要显式具体化呢?可能在某些情况下编译器无法自动推导出期望的参数类型,比如需要类型转换的情况,这时候可以强制实例化显式具体化的模板,而不是完全依赖编译器的自动推导机制:
#include <iostream>
using namespace std;
template <typename T>
void func1(T a, T b) {
cout << a << " " << b << endl;
}
template <>
void func1<short>(short a, short b) {
cout << "func1" << endl;
}
void func1(short a, short b) {
cout << "another func1";
}
int main() {
int x = INT_MAX;
int y = INT_MAX;
func1(x, y); //使用通用模板
func1<short>(x, y); //使用显式具体化
return 1;
}
当然这个例子不太具有代表性...理解意思即可。