开发者

C++ Function Overloading Similar Conversions

I'm getting an error which says that two overloads have similar conversions开发者_如何学JAVA. I tried too many things but none helped.

Here is that piece of code

CString GetInput(int numberOfInput, BOOL clearBuffer = FALSE, UINT timeout = INPUT_TIMEOUT);
CString GetInput(int numberOfInput, string szTerminationPattern, BOOL clearBuffer = FALSE, UINT timeout = INPUT_TIMEOUT);

I can't understand how could string be equal to long?

I'm using Visual C++ 6 (yep I know its old, I'm working on legacy code, so I'm pretty much helpless)

EDIT: The line of code that is triggering the error is

l_szOption = GetInput(13, FALSE, 30 * 10);


The problem is caused by the fact that you are supplying the timeout argument as a signed integer value, which has to be converted to an unsigned one for the first version of the function (since the timeout parameter is declared as UINT).

I.e. the first version of the function requires a conversion for the third argument, while the second version of the function requires a conversion for the second argument (FALSE, which is just 0, to string). In this case neither function is better than the other and overload resolution fails.

Try explicitly giving the third argument the unsigned type

l_szOption = GetInput(13, FALSE, 30U * 10);

or

l_szOption = GetInput(13, FALSE, (UINT) 30 * 10);

(whichever you prefer) and the code should compile as expected.

In other words, the compiler is absolutely right to complain about your code. Your code is indeed broken. The problem in your code has exacty the same nature as in the following simple example

void foo(int i, unsigned j);
void foo(unsigned i, int j);

int main() {
  foo(0, 0);
}

This code will also fail to compile for precisely the same reason.


GetInput(13, FALSE, 30 * 10);

My guess is that

FALSE ==> o ==> NULL is getting converted to std::string(NULL) 

hence, it cannot determine which method to instantiate.

T0 prove this check this :

GetInput(13, TRUE, 30 * 10); //it works


You are possibly passing that function a second parameter that is neither a BOOL, nor a string, but a type that could be implicitly converted to either.

A character pointer, for example.


To resolve the ambiguity when you call the function either cast the second parameter to BOOL or use string("whatever") if that is indeed std::string.


Consider following case :

BOOL is typedef of int.

GetString(10,'a'); // compiler get confused in resolving the function

whether 'a' is to be converted to BOOL or string ???

When you make function call give proper argument by using static_cast to make desired function to call.

char ch = 'a';
GetString(10,static_cast<BOOL>(ch)); // calls function with 2nd argument as BOOL

GetString(10,static_cast<string>(ch)); //calls function with 2nd argument as string
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜