【发布时间】: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&,它会改变吗? -
@WhozCraig 模板适合,为什么不适合?在最外层
max返回后使用返回值只是UB -
@sajas Check that ideone.com post 再来一次。我很好奇这是否符合您的要求。这可能看起来有点奇怪,但提供可变参数指针覆盖似乎有效。祝你好运。有趣的问题。顺便说一句,检查你的代码。我想您的文件顶部没有
using namespace std;?
标签: c++ templates overloading ambiguous-call