【问题标题】:How is a method taking const char* as argument a near match to a method taking const int&?将 const char* 作为参数的方法如何与采用 const int& 的方法接近匹配?
【发布时间】:2013-10-07 02:29:51
【问题描述】:

以下代码在我编译时会引发编译器错误。

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]

注意:const char* max(const char*, const char*)

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

【问题讨论】:

  • 试试这个const char* x = 42;,这应该回答你的问题
  • 什么编译器?它对我来说很好:coliru.stacked-crooked.com/a/d125ccc03238992e
  • 您的函数返回一个常量引用,并且您正在传递一个临时值。从技术上讲,模板甚至不适合。如果您从模板返回类型中删除const&amp;,它会改变吗?
  • @WhozCraig 模板适合,为什么不适合?在最外层max返回后使用返回值只是UB
  • @sajas Check that ideone.com post 再来一次。我很好奇这是否符合您的要求。这可能看起来有点奇怪,但提供可变参数指针覆盖似乎有效。祝你好运。有趣的问题。顺便说一句,检查你的代码。我想您的文件顶部没有using namespace std;

标签: c++ templates overloading ambiguous-call


【解决方案1】:

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

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

如果你严格需要使用命名空间std,你可以强制root命名空间调用(在main()中做的方式):

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

【讨论】:

    猜你喜欢
    • 2020-04-04
    • 2014-03-02
    • 1970-01-01
    • 2012-04-08
    • 1970-01-01
    • 2010-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多