将 const char* 作为参数的方法如何与采用 const int& 的方法接近匹配?
How is a method taking const char* as argument a near match to a method taking const int&?
以下代码在编译时抛出编译器错误。
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);
}
相关文章:
- 从 const 对象访问非 const 方法
- 为什么我可以调用一个从const方法更改成员的方法
- 使用新的c++返回值语法的Const方法
- const_cast const 方法中的"this"将"this"分配给外部变量?
- const 方法使用引用修改对象
- 从具有相同基数的另一个派生类调用派生类的非 const 方法
- 返回非常量引用编译的 Const 方法
- C++:无法从 const 方法返回对象的shared_ptr
- 是否可以从 const 方法迭代链表
- 为什么在const和非const方法中删除代码重复不是不确定的行为
- 在使用指向 const 和非 const 方法的成员指针时减少模板专用化的数量
- "可变"变量只能由 const 方法之一可变?
- Golang中的const方法
- C++ 逻辑恒常性和 const方法的按值返回
- c++将标志添加到const方法中
- C++防止const方法通过成员指针或引用更改数据
- 为什么 const 方法不覆盖 C++ 中的非 const 方法?
- 如何在const方法中迭代映射
- 为什么没有标准化的方法来避免const方法的代码重复
- 修改 const 方法中的 pointee 值