c++文字字符串和const字符串引用参数[duplicate]

时间:2021-02-16 16:38:00

This question already has an answer here:

这个问题已经有了答案:

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.

我使用const std有两个过载函数:string&bool。我现在用文字字符串调用这个函数。bool版本被称为。这有点奇怪,这确实是个陷阱。

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");
}

1 个解决方案

#1


3  

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.

问题是您要编写的参数不是std::string类型的值(它不是std::string的文字),而是一个字符数组。

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.

不幸的是,我同意您的看法,这是一个陷阱,重载解析的规则将选择将数组转换为布尔/转换为const引用字符串。

Mind you, there are in C++ 11 actual std::string literals, I won't go into the details here.

注意,这里有c++ 11实际的std::string literals,这里我不细讲。

What fixes the overload is to convert explicitly to std::string:

修复重载的方法是显式地将其转换为std::string:

write(std::string("data")) will do the right thing.

写入(std::string(“data”))将做正确的事情。

Prevent this issue in the future. It is indeed a pitfall.

以后要避免这个问题。这确实是个陷阱。

#1


3  

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.

问题是您要编写的参数不是std::string类型的值(它不是std::string的文字),而是一个字符数组。

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.

不幸的是,我同意您的看法,这是一个陷阱,重载解析的规则将选择将数组转换为布尔/转换为const引用字符串。

Mind you, there are in C++ 11 actual std::string literals, I won't go into the details here.

注意,这里有c++ 11实际的std::string literals,这里我不细讲。

What fixes the overload is to convert explicitly to std::string:

修复重载的方法是显式地将其转换为std::string:

write(std::string("data")) will do the right thing.

写入(std::string(“data”))将做正确的事情。

Prevent this issue in the future. It is indeed a pitfall.

以后要避免这个问题。这确实是个陷阱。