Search code examples
c++c++17language-lawyerstdlanguage-design

Why does the C++17 standard not allow converting a string to a bool?


As per cppref, std::from_chars can convert a string to an integer. In C++, bool is an integral type. So I think the following code is intuitive and expressive:

auto const sv = "true"sv;
auto b = bool{};
std::from_chars(sv.data(), sv.data() + sv.size(), b); // compiler error
assert(b);

However, libc++ explicitly deleted the overloaded function:

from_chars_result from_chars(const char*, const char*, bool, int = 10) = delete;

I just wonder:

Why does the C++17 standard not allow converting a string to a bool?


Solution

  • This is LWG 3266 which points out that:

    [charconv.to.chars] does not present an overload for bool (because it is neither a signed nor unsigned integer type), so an attempt to call to_chars with a bool argument would promote it to int and unambiguously call the int overload of to_chars.

    This was not intended, since it is not obvious that the correct textual representation of a bool is 0/1 (as opposed to, say, "true"/"false").

    The user should cast explicitly if he wants the 0/1 behavior. (Correspondingly, there is no bool overload for from_chars in the status quo, and conversions do not apply there because of the reference parameter.)