I have two overload function with const std::string& and bool respectively. I am now calling the function with literal string. The bool version is called. This is a bit weird, and it is really a pitfall.
Can anyone explain why?
See the code below. The output is
Write == 1
#include <iostream>
#include <string>
void write(const std::string& name_) {
std::cout << "Write == " << name_ << std::endl;
}
void write(bool name_) {
std::cout << "Write == " << name_ << std::endl;
}
int main()
{
write("data");
}
The issue is that your argument to write is not a value of type std::string (it is not a literal of std::string) but a character array.
Unfortunately, and I agree with you that it is a pitfall, the rules of the overload resolution will pick the conversion of array to boolean over conversion to const reference to string.
Mind you, there are in C++ 11 actual std::string
literals, I won't go into the details here.
What fixes the overload is to convert explicitly to std::string:
write(std::string("data"))
will do the right thing.
Prevent this issue in the future. It is indeed a pitfall.
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