将调用哪些重载的c++函数

What overloaded C++ function will be called?

本文关键字:c++ 函数 重载 调用      更新时间:2023-10-16

主题如下:

#include <string>
#include <iostream>
void test(bool val)
{
    std::cout << "bool" << std::endl;
}
void test(std::string val)
{
    std::cout << "std::string" << std::endl;
}
int main(int argc, char *argv[])
{
    test("hello");
    return 0;
}

程序输出为bool。为什么选择bool变体?

调用bool过载需要以下转换:

const char[6] ---> const char* ---> bool

调用std::string过载需要以下转换:

const char[6] ---> const char* ---> std::string

这涉及到用户定义的转换(使用std::string的转换构造函数)。任何不带用户定义转换的转换序列都比带用户定义转换的序列优先。

当比较隐式转换序列的基本形式(如13.3.3.1中定义的)时:

  • 标准转换序列(13.3.3.1.1)是比自定义转换序列或省略号转换序列更好的转换序列,
  • […]

标准转换序列是只涉及标准转换的序列。用户定义的转换序列是涉及单个用户定义转换的序列。

这是因为"hello"具有类型const char[6],该类型会衰变成const char*,然后通过另一种标准转换转换成bool。因此,整体转换为:

const char[6] -> bool

可以通过标准转换来执行

另一方面,将const char*转换为std::string需要用户定义的转换(调用std::string的转换构造函数),在进行重载解析时,标准转换优于用户定义转换。