为什么编译器更喜欢f(const void*)到f(const std :: string&)?

oma*_*mar 46 c++ overloading stdstring string-literals overload-resolution

考虑以下代码:

#include <iostream>
#include <string>

// void f(const char *) { std::cout << "const char *"; } // <-- comment on purpose
void f(const std::string &) { std::cout << "const std::string &"; }
void f(const void *) { std::cout << "const void *"; }

int main()
{
    f("hello");
    std::cout << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

我编译了这个程序g++ (Ubuntu 6.5.0-1ubuntu1~16.04) 6.5.0 20181026:

$ g++ -std=c++11 strings_1.cpp -Wall
$ ./a.out

const void *
Run Code Online (Sandbox Code Playgroud)

请注意,注释是为了测试而存在,否则编译器使用f(const char *).

那么,为什么编译器会f(const void*)接管f(const std::string &)

Yak*_*ont 54

转换为a std::string需要"用户定义的转换".

转换为void const*不.

用户定义的转换按内置订单进行排序.