daydayup
daydayup

Reputation: 2317

C++ template overloading

I am learning overloading. What is the problem of my codes? Here is the error information In instantiation of ‘const _Tp& std::max(const _Tp&, const _Tp&, _Compare) [with _Tp = double; _Compare = double]’: /usr/include/c++/4.8/bits/stl_algobase.h:263:26: error: ‘__comp’ cannot be used as a function if (__comp(__a, __b))

    #include<iostream>
using namespace std;
template <typename T1, typename T2, typename T3> T1 max(T1,T2,T3);
template <typename T1, typename T2> T1 max(T1,T2);

template <typename T1, typename T2>
T1 max(T1 x, T2 y){
 return x+y;
}

template <typename T1, typename T2, typename T3>
T1 max(T1 x, T2 y, T3 z){
 return x+y+z;
}

int main()
{
        cout << max(1.2,2.3,3.4) << endl;
        cout << max(1,2) << endl;
}

Upvotes: 0

Views: 204

Answers (2)

Thomas Moulard
Thomas Moulard

Reputation: 5542

Another solution is to completely specify which max should be called (i.e. the one in std or the one in this file?):

#include <iostream>

using namespace std;

template <typename T1, typename T2, typename T3> T1 max(T1,T2,T3);
template <typename T1, typename T2> T1 max(T1,T2);

template <typename T1, typename T2>
T1 max(T1 x, T2 y){
 return x+y;
}

template <typename T1, typename T2, typename T3>
T1 max(T1 x, T2 y, T3 z){
 return x+y+z;
}

int main()
{
        cout << ::max(1.2,2.3,3.4) << endl;
        cout << ::max(1,2) << endl;
}

Here using ::max indicates to the compiler you want max from the root namespace.

Usually, I do not recommend this solution if it can be avoided but this may come in handy.

See https://ideone.com/PWxDT7

Upvotes: 1

R Sahu
R Sahu

Reputation: 206737

The error message from the compiler clearly indicates that the compiler is using std::max instead of the functions defined in the file. That is one more reason why you should avoid

using namespace std;

To fix your problem:

  1. Remove that line.
  2. Use std::cout and std::endl instead of just cout and endl. If you want to continue to use cout and endl, add

    using std::cout;
    using std::endl;
    

Upvotes: 3

Related Questions