SE Does Not Like Dissent
SE Does Not Like Dissent

Reputation: 1835

C++ ambiguity overloading problem

I have a class called FileProc that runs File IO operations. In one instance I have declared two functions (which are sub-functions to operator= functions), both decisively different:

const bool WriteAmount(const std::string &Arr, const long S)
{
    /* Do some string conversion */
    return true;
}

const bool WriteAmount(const char Arr[], unsigned int S)
{
    /* Do some string conversion */
    return true;
}

If I make a call with a 'char string' to WriteAmount, it reports an ambiguity error - saying it is confused between WriteAmount for char string and WriteAmount for std::string. I know what is occurring under the hood - it's attempting to using the std::string constructor to implicitly convert the char string into a std::string. But I don't want this to occur in the instance of WriteAmount (IE I don't want any implicit conversion occurring within the functions - given each one is optimised to each role).

My question is, for consistency, without changing the function format (IE not changing number of arguments or what order they appear in) and without altering the standard library, is there anyway to prevent implicit conversion in the functions in question?

I forgot to add, preferably without typecasting, as this will be tedious on function calls and not user friendly.

Upvotes: 1

Views: 710

Answers (2)

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 507105

You get the ambiguity because your second parameter is different. Trying to call it with long x = ...; WriteAmount("foo", x) will raise an ambiguity because it matches the second argument better with the first overload, but the first argument is matched better with the second overload.

Make the second parameter have the same type in both cases and you will get rid of the ambiguity, as then the second argument is matched equally worse/good for both overloads, and the first argument will be matched better with the second overload.

Upvotes: 5

Ender Wiggin
Ender Wiggin

Reputation: 424

Can't you change the second argument and cast it to unsigned int ? It should not be able to use the first function call. I have not coded in C++ for ages..

Upvotes: 0

Related Questions