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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With