Reputation:
I have just read about the overloading functions on a beginner book. Just out of curiosity I 'd like to ask whether it is safe to overload between char* and std::string.
I played with the below code and get some result. But I was not sure whether it is an undefined behavior.
void foo(std::string str) {
cout << "This is the std::string version. " << endl;
}
void foo(char* str) {
cout << "This is the char* version. " << endl;
}
int main(int argc, char *argv[]) {
foo("Hello"); // result shows char* version is invoked
std::string s = "Hello";
foo(s); // result shows std::string version
return 0;
}
Upvotes: 4
Views: 2309
Reputation: 461
Short Answer: Perfectly safe. Consider the following uses:
foo("bar");//uses c string
foo(std::string("bar") );//uses std::string
char* bar = "bar";
foo(bar);//uses c string
std::string bar_string = "bar";
foo(bar_string);//uses std::string
foo(bar_string.c_str()); //uses c string
Word of warning, some compilers (namely those with c++11 enabled) require the const keyword in parameter specification in order to allow temporary strings to be used.
For instance, in order to get this: foo("bar"); You need this: void foo(const char* bar);
Upvotes: 3
Reputation: 110658
Yes, it's safe, as long as you make it const char*
, and actually often useful. String literals cannot be converted to char*
since C++11 (and it was deprecated before that).
The const char*
overload will be picked for a string literal because a string literal is a const char[N]
(where N
is the number of characters). Overloads have a kind of priority ordering over which one will be picked when multiple would work. It's considered a better match to perform array-to-pointer conversion than to construct a std::string
.
Why can overloading std::string
and const char*
be useful? If you had, for example, one overload for std::string
and one for an bool
, the bool
would get called when you passed a string literal. That's because the bool
overload is still considered a better match than constructing a std::string
. We can get around this by providing a const char*
overload, which will beat the bool
overload, and can just forward to the std::string
overload.
Upvotes: 8