Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ambiguous call to overloaded function

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?

like image 288
Martin Brandl Avatar asked Feb 21 '12 12:02

Martin Brandl


1 Answers

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.

like image 184
James Kanze Avatar answered Oct 12 '22 13:10

James Kanze