重载函数调用不明确

7

我有两个函数:

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));

它们中的一个比另一个更好吗?还有其他解决方法吗?

1
static_cast 比 C 风格的强制类型转换更好,只要适用。 - iammilind
4
@iammilind size_t(0) 不是C风格的强制类型转换。它会构造一个新的 size_t,其值为 '0'。 - Martin Brandl
为什么?在指针或引用方面可能存在问题时,static_cast 优于 C 风格的转换。否则...当您想要 MyClass 的临时实例时,您会写 static_cast< MyClass >( 42 ) 还是 MyClass( 42 ) - James Kanze
@JamesKanze,...在适用的情况下 - iammilind
@MrLister,根据构建目标选择使用DoSomething(0ul)DoSomething(0ull)。有点混乱,是吧? - Janusz Lenar
显示剩余2条评论
3个回答

7
这段内容有歧义,因为 0int 而不是 size_t类型。它可以转换为 size_t 或指针,所以如果你有两者的重载函数,那么就会产生冲突。一般而言,我建议如果你有重载函数,并且其中一个能够接受整型,你应该加入一个 int 的重载函数,例如:
inline void DoSomething( int aiValue )
{
    DoSomething( static_cast<size_t>( aiValue ) );
}

默认情况下,整数字面量的类型为 int(除非它们太大而无法放入 int 中),通过提供精确匹配,您可以避免任何歧义。


1
#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隐式转换为nullpointer的整数类型。例如,null()函数避免了这种情况,因为结果不是编译时常量。


1

歧义原因: NULL 具有数字值 0

如果您想在传递 0 作为参数时使用 void DoSomething( const tchar* apsValue ),则可以使用 nullptr。 请查看此 什么是 nullptr?


但是NULL不是这个问题的歧义之处; 0才是。新的nullptr在这里也无济于事,因为目标从来就不是调用函数的指针版本。 - Rob Kennedy
同意!但编译器发现它模棱两可,因为它可能是NULL的值,也可能只是值为0的“int”。我会尝试重新表述。 - omggs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接