Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Literal string and const string reference argument [duplicate]

Tags:

c++

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");
}
like image 585
WeidongLian Avatar asked Jun 23 '15 00:06

WeidongLian


1 Answers

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.

like image 183
TheCppZoo Avatar answered Sep 20 '22 20:09

TheCppZoo