1
votes
#include <iostream>
using std::cout;
using std::endl;

#include <string>
using std::string;

template <class T>
T max(T const& t1, T const& t2) {
    return t1 < t2 ? t2 : t1;
}

int main() {
    cout << max(1, 2) << endl;
    cout << max<double>(1.2, 2) << endl;
    string s1 = "hello";
    string s2 = "world";
 -->   cout << max(s1, s1) << endl;
}

On the line with arrow, it complains about: "more than one instance of function template "max" matches the argument list: -- function template "const _Tp &std::__1::max(const _Tp &__a, const _Tp &__b)"-- function template "T max(const T &t1, const T &t2)" -- argument types are: (std::__1::string, std::__1::string)"

I am confused since both of them are string, and not sure what else the template can match of.

1
Collision with std::max? What happens if you change the name?Dave S

1 Answers

2
votes

The max function is in conflict with the std::max function found via ADL. To fix that, you can replace the call by a qualified lookup:

cout << ::max(s1, s1) << endl;

You can also surround the function name with parenthesis to disable ADL:

cout << (max)(s1, s1) << endl;

Integers have no namespaces so they are not subject to ADL, hence why you haven't seen the problem with those.