C++ 对重载函数的不明确调用

C++ 对重载函数的不明确调用,c++,overloading,static-cast,C++,Overloading,Static Cast,我有两个职能: void DoSomething( const tchar* apsValue ) void DoSomething( size_t aiValue ) 现在我想将“0”作为大小传递\u t: DoSomething(0); 编译器抛出错误:“对重载函数的调用不明确” 为了解决这个问题,我可以使用静态_cast,例如: DoSomething(static_cast<size_t>(0)); 其中一个比另一个好吗?有没有其他方法可以解决这个问题?这是不明确的,因

我有两个职能:

void DoSomething( const tchar* apsValue )
void DoSomething( size_t aiValue )
现在我想将“0”作为大小传递\u t:

DoSomething(0);
编译器抛出错误:“对重载函数的调用不明确”

为了解决这个问题,我可以使用静态_cast,例如:

DoSomething(static_cast<size_t>(0));

其中一个比另一个好吗?有没有其他方法可以解决这个问题?

这是不明确的,因为
0
的类型是
int
,而不是
size\u t
。它可以转换 设置为
size\u t
或指针,因此如果这两个值都有重载, 这是模棱两可的。一般来说,如果你有 重载函数,其中一个可以采用整数类型,您可以添加
int
的重载可能是:

inline void DoSomething( int aiValue )
{
    DoSomething( static_cast<size_t>( aiValue ) );
}
inline void DoSomething(int aiValue)
{
剂量测量(静态施法(aiValue));
}
默认情况下,整型文字的类型为
int
(除非它们太大而无法 适合于
int
),通过提供精确匹配,可以避免任何
歧义。

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

如果在传递
0
作为参数时希望
void DoSomething(const tchar*apsValue)
,则
nullptr
将非常有用。 选中此项

#包括
#包括
使用名称空间std;
void DoSomething(char const*apsValue){cout(DoSomething)(0);
}

这似乎令人惊讶,但这不仅仅是隐式类型转换在起作用。另外,整型编译时常量0隐式转换为null指针。例如,
null()
函数避免了这种情况,因为结果不是编译时常量。

静态类型转换在适用的情况下比c样式转换更好。@iammilind size\u t(0)不是c样式转换。它构造了一个新的大小\u t,其中“0”为value@iammilind为什么?<代码>静态类型转换比C样式转换更可取,因为C样式转换可能存在以下问题:指针或引用的类型转换。否则。。。当您想要一个
MyClass
的临时实例时,您是否会编写
static\u cast(42)
MyClass(42)
?在这种特定情况下,您可能能够为大小\u t编写
DoSomething(0u)
,但这不是类似情况的一般解决方案。@JamesKanze,
…在适用的情况下
,但
NULL
不是该问题歧义的原因<代码>0无效。新的
nullptr
在这里没有帮助,因为目标是无论如何都不要调用函数的指针版本。同意!但是编译器发现它不明确,因为它可能是NULL的值,或者只是
int
的值是
0
。我会尝试重新措辞。
inline void DoSomething( int aiValue )
{
    DoSomething( static_cast<size_t>( aiValue ) );
}
#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 );
}