对重载函数的调用不明确

ambiguous call to overloaded function

本文关键字:调用 不明确 函数 重载      更新时间:2023-10-16

我有两个函数:

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到底是什么?