【发布时间】:2015-10-13 06:18:06
【问题描述】:
我创建了一个具有相同参数的模板专用函数和一个非模板函数。由于实际上两者都是相同的功能,我不确定 C++ 编译器将如何运行它,因为现在它有两个相同的功能,一个是专门的模板,另一个是非模板。我原以为这会导致编译器错误,因为编译器会找到两个具有相同参数和返回类型的函数(在本例中为 void foo(string) )。但看起来非模板版本是在调用它时执行的版本。 那么这样做有优先级吗?
如果我误解了,请告诉我。
代码:这将打印“字符串非模板”
#include <iostream>
#include <string>
using namespace std;
template<typename T>
void foo(T input)
{
cout <<"Generic Template"<<endl;
}
template<>
void foo<string>(string input)
{
cout <<"String Template"<<endl;
}
void foo(string input)
{
cout <<"String Non-Template"<<endl;
}
int main() {
string input = "abc";
foo(input);
return 0;
}
【问题讨论】:
-
请注意,您可以通过
foo<std::string>(input);调用模板版本(甚至foo<>(input);)