What overloaded C++ function will be called?

c++, overloading

Solution

To call the `bool` overload requires the following conversion:

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

To call the `std::string` overload requires the following conversion:

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

This involves a user-defined conversion (using the conversion constructor of `std::string`). Any conversion sequence without a user-defined conversion is preferred over a sequence with a user-defined conversion.

When comparing the basic forms of implicit conversion sequences (as defined in 13.3.3.1):

- a standard conversion sequence (13.3.3.1.1) is a better conversion sequence than a user-defined conversion sequence or an ellipsis conversion sequence, and

- [...]

A standard conversion sequence is one involving only standard conversions. A user-defined conversion sequence is one involving a single user-defined conversion.

Problem

Here is the subject of the topic: ``` #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; } ``` The output of the program is `bool`. Why the `bool` variant selected?

Original source

Related problems