Still Learning
Still Learning

Reputation: 501

Function overloading doesn't work with templates in C++?

I am learning C++, and I have come across the usage of Templates.

So I tried to implement the below two functions using Templates as follows :

template <typename T>
T max(T a, T b){
    return (a > b) ? a : b;
}

template <typename T>
T max(T a, T b, T c){
    return max( max(a, b), c);
}

Well, the above implementation is throwing some errors during the compilation.

This is what the error looks like :

templateEx.cpp:13:14: error: call to 'max' is ambiguous
        return max( max(a, b), c);
                    ^~~
templateEx.cpp:17:22: note: in instantiation of function template specialization
      'max<int>' requested here
        cout<<"2, 3, 4 : "<<max(2,3,4);
                            ^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/algorithm:2654:1: note: 
      candidate function [with _Tp = int]
max(const _Tp& __a, const _Tp& __b)
^
templateEx.cpp:7:3: note: candidate function [with T = int]
T max(T a, T b){
  ^
1 error generated.

But on the flip side, if I don't use any Template, and I use plain function overloading like below example :

int max(int a, int b){
    return (a > b) ? a : b;
}

int max(int a, int b, int c){
    return max( max(a, b), c);
}

The above code compiles error free.

Can someone please explain this?

Where am I going wrong?

Upvotes: 1

Views: 84

Answers (1)

Curious
Curious

Reputation: 21510

There is a std::max which is what you are conflicting with. Do you have a using namespace std; or using std::max somewhere in your code?

Overloading a template function with different number of parameters should work.

Upvotes: 6

Related Questions