在下面的代码片段中,
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;
}
我想修改模板,通过传递 float 以外的任何类型将打印“all”,传递 float 将打印“float”。我不想要模板特化,而是有部分特化,它会根据输入类型采取相应的行动。我该怎么办。提前致谢。
好吧,我目前面临的情况是, 我需要定义以下内容,
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"
像上面这样的某种分组,其中很少有人应该调用部分特化实现,而其他人应该调用默认实现。
最佳答案
您可以将函数重载与模板相结合。所以:
#include <iostream>
template<typename T>
void func(T& t)
{
std::cout << "all" << std::endl;
}
void func(float& f)
{
std::cout << "float" << std::endl;
}
int main()
{
int i; float f;
func(i); // prints "all"
func(f); // prints "float"
return 0;
}
关于c++ - 函数模板的部分特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5002616/