q126y
q126y

Reputation: 1671

Function overloading and templates

#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;
}

The above code throws the following error.

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>]

Since, function overloading only accounts for the function name, parameter type list and the enclosing namespace. Why is this error being thrown?

Upvotes: 2

Views: 46

Answers (1)

Weak to Enuma Elish
Weak to Enuma Elish

Reputation: 4637

The call to Foo<int>(2) could be either:

ReturnType Foo(ArgumentType arg); //with ReturnType = int, ArgumentType deduced as int

or

string Foo(ArgumentType arg); //with ArgumentType = int

The compiler can't tell which one you wanted because they both have the same arguments:

int Foo(int);
string Foo(int);

Upvotes: 2

Related Questions