3

The following code throws compiler error when I compile it.

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

// maximum of two C-strings (call-by-value)
inline char const* max (char const* a, char const* b)
{
    return strcmp(a,b) < 0 ? b : a;
}

// maximum of three values of any type (call-by-reference)
template <typename T>
inline T const& max (T const& a, T const& b, T const& c)
{
    return max (max(a,b), c); 
}

int main ()
{
    ::max(7, 42, 68);  
}

On compilation I get the error :

error: call of overloaded 'max(const int&, const int&)' is ambiguous

note: candidates are:

note: const T& max(const T&, const T&) [with T =int]

note: const char* max(const char*, const char*)

How does max(const char*, const char*) becomes a near match for max(const int&, const int &) when we have the template method that matches the call?

4

1 回答 1

1

我敢打赌你using namespace std的代码里有。删除它,你会没事的。

比较: http: //ideone.com/Csq8SVhttp://ideone.com/IQAoI6

如果您严格需要使用命名空间 std,则可以强制根命名空间调用(在 中执行的方式main()):

template <typename T>
inline T const& max (T const& a, T const& b, T const& c)
{
    return ::max(::max(a,b), c); 
}
于 2013-10-08T09:36:19.940 回答