1.模板函数不能是虚函数
这个还可以理解,参考c++模板函数可以是虚函数吗
如果模板函数是虚函数,会严重降低编译器处理效率,可以知道C++连类的声明顺序都是严格要求的,这样的语法更不能允许了。
2.模板函数和偏特化
(1)经过测试:普通模板函数支持偏特化;
(2)非内联类的模板函数支持偏特化;
(3)内联类的模板函数不支持偏特化
#include <iostream>
using namespace std;
class father
{
public:
template <class T>
void test(T a);
};
class child:public father
{
public:
void test(double a)
{
cout<<"my signature"<<endl;
}
int a;
};
template <class T>
void father::test(T a)
{
cout<<a<<endl;
}
template <>
void father::test(double a)
{
cout<<"double tag"<<endl;
}
int main(void)
{
father *c = new child();
c->test(123);
c->test(123.0);
}
上例输出:
123
double tag
如果像下面这样写,gcc通不过编译:
#include <iostream>
using namespace std;
class father
{
public:
template <class T>
void test(T a)
{
cout<<a<<endl;
}
template <>
void test(T a,DoubleTag tag)
{
cout<<"my signature"<<endl;
}
template <class T>
void test(T a)
{
test_in(a,typename TagPatch<T>::Tag {});
}
};
class child:public father
{
public:
void test(double a)
{
cout<<"my signature"<<endl;
}
int a;
};
int main(void)
{
father *c = new child();
c->test(123);
c->test(123.0);
}
//编译错误:提示这个位置不能模板偏特化
内联函数的偏特化可以有解决方案:
//上例的内联偏特化一种非常邪门的模拟方案
#include <iostream>
using namespace std;
template <class T>
void test(T a)
{
cout<<a<<endl;
}
template <>
void test(double a)
{
cout<<"double tag"<<endl;
}
struct NormalTag {};
struct DoubleTag {};
template <class T>
struct TagPatch
{
using Tag = NormalTag;
};
template <>
struct TagPatch<double>
{
using Tag = DoubleTag;
};
class father
{
public:
template <class T>
inline void test_in(T a,NormalTag tag)
{
cout<<a<<endl;
}
template <class T>
inline void test_in(T a,DoubleTag tag)
{
cout<<"my signature"<<endl;
}
template <class T>
void test(T a)
{
test_in(a,typename TagPatch<T>::Tag {});
}
};
class child:public father
{
public:
void test(double a)
{
cout<<"my signature"<<endl;
}
int a;
};
int main(void)
{
father *c = new child();
c->test(123);
c->test(123.0);
}
参考:c++模板函数不能偏特化
根据上面的链接,猜测模板函数偏特化不是c++标准,非内联函数能够偏特化的实现是gcc的实现,而没有实现内联版本。(只是猜测)