字符串文字匹配bool重载,而不是std::String
String literal matches bool overload instead of std::string
我正在尝试编写一个C++类,它有一些重载方法:
class Output
{
public:
static void Print(bool value)
{
std::cout << value ? "True" : "False";
}
static void Print(std::string value)
{
std::cout << value;
}
};
现在假设我调用方法如下:
Output::Print("Hello World");
这是的结果
真实
那么,为什么当我定义了该方法可以接受布尔值和字符串时,当我传入非布尔值时,它会使用布尔重载呢?
编辑:我来自一个C#/Java环境,所以对C++来说是全新的
"Hello World"
是一个类型为"array of 12 const char
"的字符串文字,它可以转换为"指向const char
的指针",然后再转换为bool
。这正是正在发生的事情。编译器更喜欢使用std::string
的转换构造函数。
涉及转换构造函数的转换序列称为用户定义的转换序列。从"Hello World"
到bool
的转换是标准转换序列。标准规定,标准转换序列总是优于用户定义的转换序列(§13.3.3.2/2):
标准转换序列(13.3.3.1.1)是比用户定义的转换序列或省略号转换序列更好的转换序列
这种"更好的转换序列"分析是针对每个可行函数的每个参数(并且只有一个参数)进行的,并且通过重载解析来选择更好的函数。
如果你想确保调用std::string
版本,你需要给它一个std::string
:
Output::Print(std::string("Hello World"));
不确定为什么没有人发布这篇文章,但您可以添加另一个重载,将const char*转换为std::string。这使呼叫者不必为此担心。
class Output
{
public:
static void Print(bool value)
{
std::cout << value ? "True" : "False";
}
static void Print(std::string value)
{
std::cout << value;
}
// Just add the override that cast to std::string
static void Print(const char* value)
{
Output::Print(std::string(value));
}
};
FWIW,如果您不想为const char*
添加重载,则可以通过这种方式(如果可以使用模板)对其进行处理。
#include <iostream>
#include <string>
#include <type_traits>
template <typename Bool,
typename T = std::enable_if_t<std::is_same<Bool, bool>{}>>
void foo(Bool)
{
std::cerr << "booln";
}
void foo(const std::string&)
{
std::cerr << "stringn";
}
int main()
{
foo("bar");
foo(false);
}
由于C++14,我们有来自std::string_literals
命名空间的operator""s
,它可以用来告诉编译器绑定到string
(或C++17中的string_view
)重载:
using namespace std::string_literals;
Output::Print("Hello World"s);
打印:Hello World
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- 使用 std::string () const 函数启动线程或未来
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 如何更改大小(std::string)
- std::string 的对象真的可以移动吗?
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 无法从 std::string 中提取C++ Unicode 符号
- std::string 构造函数如何处理固定大小的 char[]?
- 真的没有来自 std::string_view 的 std::string 的显式构造函数吗?
- 将C++ std::string 转换为 UTF-16-LE 编码的字符串
- 重载 + 自己的类和 std::string 的运算符
- 如何使用 std::string 作为 QHash 的键?
- 将日语 wstring 转换为 std::string
- 可以从std::string继承以提供类型一致性吗
- 构造函数采用std::string_view与std::string并移动
- 在共享缓冲区内存中创建 ::std::string 对象
- std::string.size() 未知行为
- Valgrind 在 std::string::swap 中报告 SIGILL