为什么带引号的字符串在 std::string 之前匹配 bool 方法签名? [英] Why does a quoted string match bool method signature before a std::string?

查看:16
本文介绍了为什么带引号的字符串在 std::string 之前匹配 bool 方法签名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下方法:

// Method 1
void add(const std::string& header, bool replace);

//Method 2
void add(const std::string& name, const std::string& value);

看起来下面的代码最终会调用方法 1 而不是方法 2:

It would appear that the following code will end up calling method 1 instead of method 2:

something.add("Hello", "World");

我最终创建了另一个如下所示的方法:

I ended up creating another method that looks like this:

//Method 3
void MyClass::add(const char* name, const char* value) {
    add(std::string(name), std::string(value));
}

它奏效了.因此,当一个方法接受一个带引号的字符串"时,它似乎会按以下顺序匹配:

It worked. So it would seem that when a method accepts a "quoted string" it will match in the following order:

  1. const char*
  2. bool
  3. std::string

为什么在 std::string 之前将带引号的字符串视为 bool ?这是通常的行为吗?我为这个项目编写了大量代码,并且没有遇到任何其他问题,因为选择了错误的方法签名......

Why would a quoted string be treated as a bool before a std::string? Is this the usual behavior? I have written a decent amount of code for this project and haven't had any other issues with the wrong method signature being selected...

推荐答案

我的猜测是从指针到 bool 的转换是一种隐式原始类型转换,其中转换为 std::string 需要构造函数的调用和临时的构造.

My guess is the conversion from pointer to bool is an implicit primitive type conversion, where the conversion to std::string requires the call of a constructor and the construction of a temporary.

这篇关于为什么带引号的字符串在 std::string 之前匹配 bool 方法签名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆