A C++ library declares print(bool) and print(const std::string&); why does print("hello") print true, and how do you block it?
answer
- standard beats user-defined
- array to pointer to bool
- the string needs a constructor
- an exact overload or = delete
basics
~20 sThe literal reaches bool through standard conversions (array-to-pointer, then pointer-to-bool), while std::string needs a user-defined conversion, and any standard conversion sequence beats a user-defined one. Add an exact print(const char*) overload, or declare it = delete.
solid answer
~40 s`"hello"` is a `const char[6]`. To call `print(bool)` it decays to `const char*` and then takes a **boolean conversion**: a standard conversion sequence of Conversion rank. To call `print(const std::string&)` it must go through `std::string`'s converting constructor, a **user-defined conversion sequence**. The standard ranks *every* standard conversion sequence above *every* user-defined one, so `print(bool)` wins and prints `true`. Switching the parameter to `std::string_view` does not help, since that is also a user-defined conversion. The fix is an overload that matches the literal exactly: either a forwarding `print(const char*)`, or `void print(const char*) = delete;`, which makes the call an error. A deleted function still takes part in overload resolution, so if it is selected the program is ill-formed. C++26 adds `= delete("reason")` to put a message in the diagnostic.
code
cpp · 13 lines#include <cstdio>
#include <string>
void print(bool b) { std::puts(b ? "print(bool): true" : "print(bool): false"); }
void print(const std::string& s) { std::printf("print(string): %s\n", s.c_str()); }
#ifdef FIX
void print(const char* s) { print(std::string(s)); } // exact match for literals
#endif
int main() {
print("hello"); // without FIX: const char[6] -> const char* -> bool
print(std::string("hello")); // exact match for the string overload
}go deeper
Remember that a string literal can silently call a bool overload, and that adding a const char* overload fixes it.
Explain the order of conversion-sequence forms, standard before user-defined before ellipsis, and why string_view does not change the result.
Show how = delete blocks an unwanted call, why deleted overloads still compete and can create ambiguity, and how a deleted catch-all template restricts an API to one type.
Decide which implicit conversions a public API should reject at compile time, and whether the team adopts C++26 deletion messages when the toolchain allows it.
## Why a string literal prefers bool Overload resolution compares the **form** of each implicit conversion sequence before it compares ranks: 1. A **standard conversion sequence** (built from at most one conversion of each category the standard defines) is better than 2. a **user-defined conversion sequence** (a standard sequence, then one converting constructor or conversion function, then another standard sequence), which is better than 3. an **ellipsis** conversion sequence (matching `...`). For `print("hello")` the argument has type `const char[6]`: - **To `bool`**: array-to-pointer conversion (Exact Match rank), then a boolean conversion from `const char*` to `bool` (Conversion rank). The whole thing is a *standard* conversion sequence. - **To `const std::string&`**: the literal must be turned into a temporary `std::string` by the converting constructor `basic_string(const char*)`. That is a *user-defined* conversion sequence. Rank never gets compared, because the forms differ: a standard sequence of any rank beats a user-defined one. The non-null pointer converts to `true`, and the program prints `print(bool): true`. Clang accepts this with no warning under `-Wall -Wextra`. The same happens with `std::string_view`, whose constructor from `const char*` is also user-defined, and with any class type parameter that a literal reaches through a constructor. C++20 made pointer-to-`bool` a **narrowing** conversion, but that rule only applies to list-initialization such as `bool b{"x"}`. It does not change overload ranking, so the call above still picks `print(bool)` in C++20 and C++23. ## Fixing it with an exact overload The durable fix is to give the literal a route that beats the boolean conversion: - Add `void print(const char* s) { print(std::string(s)); }`. The array-to-pointer decay is an Exact Match, which beats the Conversion-rank path to `bool`, so literals reach the string behaviour. - Or make the parameter a template that only accepts the types you mean, a technique covered with templates and constraints. ## Blocking it with = delete When the right behaviour is "this call should not compile", declare the overload **deleted**: ```cpp void print(bool); void print(const std::string&); void print(const char*) = delete; ``` A deleted function is **declared**, so it is a candidate and takes part in overload resolution like any other. The standard makes any construct that designates a deleted function, other than its declaration, ill-formed. For an overload set, only the function overload resolution selects counts as designated. Here the deleted overload is the best match, so clang reports `call to deleted function 'print'`. C++26 adds a reason string, `= delete("pass a std::string")`, which the standard recommends compilers include in the diagnostic. Apple clang 21 prints it under `-std=c++2c`. ## The deleted-overload trap Because deleted overloads compete normally, adding them can break calls that used to work. In the code example, `set_timeout_ms(long)` happily accepted `250` before. After adding deleted `double` and `bool` overloads, `int` to `long`, `int` to `double` and `int` to `bool` are all Conversion rank, and the call becomes **ambiguous**. Remember three things: - A deleted overload only catches arguments for which it is the **best** match. - To block *every* type except one, the usual form is a deleted function template, `template <class T> void set_timeout_ms(T) = delete;`, beside the non-template: any other type deduces an exact match to the template and hits the deletion. - Re-test existing call shapes whenever an overload is added, deleted or not. ## The same hierarchy elsewhere - **Any object pointer** reaches a `bool` overload the same way: `print(&counter)` prints `true`. Clang does warn here (`-Wpointer-bool-conversion`, on by default, because the address "will always evaluate to 'true'"), but it says nothing for a string literal argument. - A **`std::unique_ptr`** does not slide into `print(bool)`, because its `operator bool` is `explicit` and only applies in conditions; with no other viable overload the call fails to compile. - Matching a C-style `...` parameter ranks last of all, below any user-defined conversion. ## When this matters This bug ships in logging, configuration and serialization APIs, where a `bool` flag overload and a string overload live together. Interviewers use it to test whether a candidate knows the conversion-sequence hierarchy rather than guessing from what "looks closer".
- Does changing the string parameter to std::string_view fix print("hello")?No. Constructing a `std::string_view` from `const char*` is still a user-defined conversion, so the standard conversion sequence to `bool` keeps winning. Only an overload the literal reaches by a standard conversion, such as `print(const char*)`, changes the result.
- Why can a deleted overload make a previously valid call ambiguous?A deleted function is still a declared candidate. If it ties with the function you wanted, for example `int` converting to both `long` and a deleted `double` at Conversion rank, overload resolution cannot choose and reports ambiguity instead of falling back to the non-deleted one.
- How do you allow exactly one parameter type and reject all others?Pair the real function with a deleted catch-all template: `void set_timeout_ms(long); template <class T> void set_timeout_ms(T) = delete;`. A `long` argument prefers the non-template on a tie, while any other type deduces an exact match to the deleted template.
- A string literal is converted to std::string before bool is considered
- Using std::string_view instead of std::string makes the literal pick it
- C++20's narrowing rule for pointer to bool fixed this overload
- A deleted overload is removed from the candidate set
- Adding a deleted overload can never break an existing call
Assumes C++23; = delete with a reason string is C++26 (__cpp_deleted_function 202403L), and the pointer-to-bool narrowing rule since C++20 applies only to list-initialization.