【问题标题】:Function overloading and templates函数重载和模板
【发布时间】:2015-11-24 05:26:37
【问题描述】:
#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>]

因为,函数重载只考虑函数名、参数类型列表和封闭的命名空间。为什么会抛出这个错误?

【问题讨论】:

    标签: c++ function templates overloading


    【解决方案1】:

    Foo&lt;int&gt;(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);
    

    【讨论】:

    • 但是函数是用一个模板参数调用的,模板函数ReturnType Foo(ArgumentType arg){}需要两个模板参数
    • @q126y 可以推断出第二个参数是什么,因为它是参数的类型。
    • 好的,那么错误不应该与重载有关,因为导致错误的不是重载。
    • @q126y,是函数重载。有两个函数模板名称为Foo
    • @james 但是专用模板[导致错误]具有相同的函数名称、参数列表和封闭的名称空间,因此不是函数重载的情况。如果我错了,请纠正。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-04
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多