#include <iostream>
using namespace std;
template <typename ReturnType, typename ArgumentType>
ReturnType Foo(ArgumentType arg){}
template <typename ArgumentType>
string Foo(ArgumentType arg) { cout<<"inside return 1"<<endl; return "Return1"; }
int main(int argc, char *argv[])
{
Foo<int>(2);
return 0;
}
上面的代码抛出以下错误。
In function 'int main(int, char**)':
34:18: error: call of overloaded 'Foo(int)' is ambiguous
34:18: note: candidates are:
7:12: note: ReturnType Foo(ArgumentType) [with ReturnType = int; ArgumentType = int]
20:8: note: std::string Foo(ArgumentType) [with ArgumentType = int; std::string = std::basic_string<char>]
因为,函数重载仅考虑函数名称、参数类型列表和封闭的命名空间。为什么会抛出这个错误?
最佳答案
调用Foo<int>(2)
可以是:
ReturnType Foo(ArgumentType arg); //with ReturnType = int, ArgumentType deduced as int
或
string Foo(ArgumentType arg); //with ArgumentType = int
编译器无法判断您想要哪一个,因为它们都有相同的参数:
int Foo(int);
string Foo(int);
关于c++ - 函数重载和模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33886054/