0

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;
}
2
  • That's not the full error message and using namespace std; definitely isn't helping you here (notice how the error says std::max). Commented Jul 9, 2015 at 3:48
  • BTW, according to implementation, it should be named sum, not max. Commented Jul 9, 2015 at 7:37

2 Answers 2

3

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;
    
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.