对重载函数的调用不明确
ambiguous call to overloaded function
我有两个函数:
void DoSomething( const tchar* apsValue )
void DoSomething( size_t aiValue )
现在我想将"0"作为size_t:传递
DoSomething(0);
编译器抛出错误:"对重载函数的调用不明确"
为了解决这个问题,我可以使用static_cast,例如:
DoSomething(static_cast<size_t>(0));
或者简单:
DoSomething(size_t(0));
其中一个比另一个好吗?有其他方法可以解决这个问题吗?
这是不明确的,因为0
的类型是int
,而不是size_t
。它可以转换指向size_t
或指针,因此如果两者都过载,这是模棱两可的。一般来说,我建议您重载函数,并且其中一个函数可以采用整型int
的过载,可能沿着
inline void DoSomething( int aiValue )
{
DoSomething( static_cast<size_t>( aiValue ) );
}
默认情况下,整型文字的类型为int
(除非它们太大而不能适合int
),并且通过提供精确匹配,可以避免任何模棱两可
#include <iostream>
#include <stddef.h>
using namespace std;
void DoSomething( char const* apsValue ) { cout << "ptr" << endl; }
void DoSomething( size_t aiValue ) { cout << "int" << endl;}
template< class Type > Type runtime_value( Type v ) { return v; }
int null() { return 0; }
template< class Type > Type* nullPointerValue() { return 0; }
int main()
{
// Calling the integer argument overload:
int dummy = 0;
DoSomething( size_t() );
DoSomething( runtime_value( 0 ) );
DoSomething( null( ) );
DoSomething( dummy );
static_cast< void(*)( size_t ) >( DoSomething )( 0 );
// Calling the pointer argument overload:
DoSomething( nullptr );
DoSomething( nullPointerValue<char>() );
static_cast< void(*)( char const* ) >( DoSomething )( 0 );
}
这可能看起来令人惊讶,但它不仅仅是隐式类型转换。此外,整型的编译时常数0隐式转换为null指针。例如,null()
函数避免了这种情况,因为结果不是编译时间常数。
歧义原因:NULL
具有数值0
。
如果在传递0
作为参数时需要void DoSomething( const tchar* apsValue )
,nullptr
会很有帮助。检查这个nullptr到底是什么?
相关文章:
- C++ 编译器错误:P1LinkedList.cpp:145:错误:重载的"to_string(int&)"调用不明确
- 为什么调用不明确的 ctor 时没有编译时错误?
- G++ 错误:重载的"abs(无符号 int)"的调用不明确
- 如果存在具有不同参数的继承成员,为什么对 C++ 结构函数的调用不明确?
- 错误:重载'stoi(nlohmann::basic_json<>::value_type&)'的调用不明确
- 构建 castalia 时出错:重载函数的调用不明确
- 错误:重载的"abs(double)"调用不明确
- 结构构造函数调用不明确
- 错误:对重载函数的调用不明确
- 对重载'swap(char&, char&)'的调用不明确
- 对可变模板函数的调用不明确
- C++ 编译错误:重载的"<function_name>(char*&)"调用不明确
- VS2010中具有list_of的调用不明确
- 为什么这个运算符=调用不明确
- 为什么对重载函数的调用不明确
- C++中重载运算符函数对构造函数的调用不明确
- 为什么这些重载函数调用不明确
- 重载write(int)的调用不明确
- 带有重载r值引用函数的调用不明确
- 传递0而不是1时,sfinae调用不明确