【发布时间】:2011-06-27 12:29:09
【问题描述】:
在下面的代码sn-p中,
template<typename T1>
void func(T1& t)
{
cout << "all" << endl;
}
template<typename T2>
void func(T2 &t)
{
cout << "float" << endl;
}
// I do not want this
// template<> void func(float &t)
int main()
{
int i; float f;
func(i); // should print "all"
func(f); // should print "float"
return 0;
}
我想修改模板,通过传递除浮点数以外的任何类型将打印“全部”,传递浮点数将打印“浮点数”。我不想要模板专业化,而是有部分专业化,它将根据输入类型相应地采取行动。我该怎么做。提前致谢。
好吧,我目前面临的情况是, 我需要定义以下内容,
template<typename T1>
void func(T1 &t)
{
cout << "t1" << endl;
}
template<typename T2>
void func(T2 &t)
{
cout << "t2" << endl;
}
以下调用应打印“t2”
func(int) // print "t2"
func(float) // print "t2"
func(string) // print "t2"
以下调用应打印“t1”
func(char) // print "t1"
func(xyz) // print "t1"
...
func(abc) // print "t1"
类似于上面的某种分组,其中很少有人应该调用部分专业化实现,而其他人应该调用默认实现。
【问题讨论】:
-
为什么不使用模板专业化?这就是它的用途。
-
虽然您不能部分特化模板函数,但函数特化通常是个坏主意,请参阅:gotw.ca/publications/mill17.htm
-
我不打算回答,因为:你还没有解释“int X”有什么用处。
标签: c++ templates template-specialization function-templates