c++ - 函数重载和模板

标签 c++ function templates overloading

#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/

相关文章:

c++ - 传递指针 - 用于写入流

c++ - 如何从 C++ 创建和调用多个文件中的 lua 函数

r - 将参数传递给 R 中的自定义函数和过滤器

list - Racket:用列表中的元素绘制抛物线

c++ - 从派生模板类调用函数

css - 如何使内部div将外部div向下推

c++ - 基类的未定义模板参数

c++ - 无法打印文件中的文本

c++ - 在原始类型 C++ 中返回 const 或非常量有什么区别

c++ - 创建一个为派生类实现单例的基类