Will an overloaded C ++ function be called?

Here is the topic 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 bool program. Why is bool selected?

+4
source share
2 answers

The following conversion is required to invoke bool overload:

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

The following conversion is required to call the std::string overload:

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

This is due to a custom conversion (using the std::string conversion constructor). Any sequence of transformations without a custom transform is preferred in sequence with a custom transform.

When comparing the main 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 includes only standard conversions. A user transformation sequence is a single user transformation.

+14
source

This is because "hello" is of type const char[6] , which decomposes into const char* , which, in turn, can be converted to bool using another standard conversion. Therefore, the total conversion:

 const char[6] -> bool 

It can only be performed using standard conversions.

On the other hand, converting a const char* to std::string requires a custom conversion (calling the conversion constructor std::string ), and standard conversions are preferred over custom conversions when performing overload resolution.

+6
source

All Articles