将 const char* 作为参数的方法如何与采用 const int& 的方法接近匹配?

How is a method taking const char* as argument a near match to a method taking const int&?

本文关键字:const 方法 int 接近 char 参数      更新时间:2023-10-16

以下代码在编译时抛出编译器错误。

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);  
}

在编译时,我收到错误:

错误:重载的"max(const int&, const int&)"的调用不明确

注:候选人是:

注意: const T& max(const T&

, const T&) [with T =int]

注意:常量字符* max(常量字符*,常量字符*)

当我们拥有与调用匹配的模板方法时,max(const char*, const char*) 如何成为 max(const int&, const int &) 的近似匹配?

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

比较:http://ideone.com/Csq8SV 和 http://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); 
}