wrong function being picked

后端 未结 3 1997
抹茶落季
抹茶落季 2021-01-03 19:38

I was trying to clean up some code that uses char* with std::string and ran into a problem that is illustrated by the following code.



        
3条回答
  •  耶瑟儿~
    2021-01-03 20:01

    Surprising as this behaviour is, the compiler is compliant: char* to bool conversion is preferred over the conversion to std::string.

    Read more here.

    The exact rules are spelled out in the C++ standard. They're surprisingly complicated, but the following paragraph is crucial here:

    C++11 13.3.3.2 Ranking implicit conversion sequences [over.ics.rank]

    2 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

    char*-to-bool requires a "standard conversion sequence" whereas char*-to-string requires a "user-defined conversion sequence". Therefore, the former is preferred.

提交回复
热议问题