很多地方说“函数模板不能偏特化”,这个如果是按照03的标准来说,应该没有问题。(现在没有用之前的编译器测,如果这里有问题,请麻烦指正)。
于是抱着怀疑的态度,测试了一下,等着编译器报错:
template.h
#ifndef TEMPLATE_H
#define TEMPLATE_H
#include <iostream>
#include <map>
template <typename T, typename U>
void tfunc(T& a, U& b)
{
std::cout << "1.tfunc 泛化版本函数" << std::endl;
}
template <>
void tfunc(int& a, int& b)
{
std::cout << "2.tfunc 全特化版本函数" << std::endl;
}
template <typename T>
void tfunc(T& a, double& b)
{
std::cout << "3.tfunc 偏特化版本函数" << std::endl;
}
#endif // TEMPLATE_H
main.cpp
#include "template.h"
int main()
{
int a1 = 1;
double b1 = 3.2;
double b2 = 4.2;
tfunc(a1, b1);
tfunc(a1, a1);
tfunc(b1, b2);
getchar();
return 0;
}
运行结果:
换了个编译器,用Qt中带的MingW7.5编译器运行了一下,一样的结果。
突然间就迷茫了,网上的那些说法难道都是人云亦云。
在C++ Templates第二版(英文版)中看到了证据:
以后对C++模板编程了解多一些,再来对本文章进行总结