views:

285

answers:

5

Refactoring legacy code, I came across this function (pseudocode):

int getMessage( char * buffer, int size = 300 );

Gee, look at that buffer just waiting to overflow. So I came up with a function using std::string, and thought it would be nice to use function overloading:

int getMessage( std::string & buffer );

So far, so good. But when I try to call the function with a string:

std::string buffer;
int rc = getMessage( buffer );

I get this error:

cannot convert 'std::string' to 'char*' for argument '1' to 'int getMessage(char*, int)'

Obviously, the compiler (GCC 4.1.2) tries hard to convert std::string to char* to satisfy the first function's parameter list (using the default value to satisfy the second parameter), gives up, but doesn't try the second function...

I wouldn't have a problem working around this issue, but I'd like to know why this fails, and whether there would be a way to make it work as intended.

+3  A: 

It works as expected on my GCC 4.3.2, maybe you misspelled the name of the overload? There's no conversion from std::string to char*, so the compiler shouldn't have any problems choosing the correct overload.

$ cat test.cpp
#include <string>
#include <stdio.h>

int getMessage( char * buffer, int size = 300 )
{
printf("1\n");
return 1;
}

int getMessage( std::string & buffer )
{
printf("2\n");
return 2;
}

int main()
{
std::string buffer;
buffer = "Hello";
int rc = getMessage( buffer );
}

$ g++ test.cpp -Wall -pedantic
test.cpp: In function ‘int main()’:
test.cpp:20: warning: unused variable ‘rc’
$ ./a.out 
2
$ $ g++ -v 2>&1|tail -n1
gcc version 4.3.2 (Ubuntu 4.3.2-1ubuntu12) 
$
Kasprzol
+1  A: 

Hmmm. There is no implicit conversion from std::string to char*, so that can't be your problem. Are you sure your new function is visible at the call site?

You said this is pseudo-code. Are you leaving something out? Are these template functions or member functions? Please post more of the code or try to boil it down to a smaller test case.

Brian Neal
+1  A: 

My guess is that the overload for the string version of the function isn't visible where you called it. Are you sure that it is in the correct header file, and is spelled correctly?

KeithB
+1  A: 

Do you have a declaration of `int getMessage( std::string & buffer );' in scope? You are hitting this error because the proper function is not being found.

dirkgently
+1  A: 

As always, once the problem is solved, the solution is painfully trivial and should have been obvious all along.

So I came up with a function using std::string...

...in my working directory, which compiled just fine, but -I and -L in my makefile were still pointing at the previous version of the library, which was blissfully unaware of the new function.

Sorry for the bother. I've been an idiot. I hope this doesn't become a habit. ;-)

DevSolar
We all have our moments! I have them almost everyday, more like a bad toothache that just wouldn't go away. Cheers!
dirkgently