ambiguous call to overloaded function

六月ゝ 毕业季﹏ 提交于 2021-02-20 06:44:07

问题


I have two functions:

void DoSomething( const tchar* apsValue )
void DoSomething( size_t aiValue )

Now I want to pass '0' as a size_t:

DoSomething(0);

The compiler throws an error: "ambiguous call to overloaded function"

To solve this, I can use static_cast, for instance:

DoSomething(static_cast<size_t>(0));

Or simple:

DoSomething(size_t(0));

Is one of them better than the other? Are there any other approaches to solve this?


回答1:


It's ambiguous because 0 has type int, not size_t. It can convert to either size_t or a pointer, so if you have an overload of both, it's ambiguous. In general, I would recommend that if you have overloaded functions, and one of them can take an integral type, you add an overload for int, maybe along the lines of:

inline void DoSomething( int aiValue )
{
    DoSomething( static_cast<size_t>( aiValue ) );
}

Integral literals have type int by default (unless they're too big to fit into an int), and by providing an exact match, you avoid any ambiguity.




回答2:


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

It might seem surprising that this works, but it's not just implicit type conversion at work. It's also that a compile time constant 0 of integral type converts implicitly to nullpointer. E.g., the null() function avoids that because the result is not a compile time constant.




回答3:


Reason for ambiguity: NULL has the numeric value 0.

If in case you want void DoSomething( const tchar* apsValue ) when passing 0 as the parameter, nullptr will be helpful. Check this What exactly is nullptr?



来源:https://stackoverflow.com/questions/9377601/ambiguous-call-to-overloaded-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!