'Why {} is better candidate to be int than string for C++ overload resolution? [duplicate]
Overload resolution favours to consider {} as being of some fundamental type as opposed to some container.
For example:
#include <iostream>
#include <string>
void foo(const std::string&) {std::cout << "string\n";}
void foo(int) {std::cout << "int\n";}
int main() { foo({}); }
That compiles without any diagnostics and outputs:
int
https://godbolt.org/z/zETfrs5as
If to comment out the int overload then it works fine with string.
The question is why? For programmer's standpoint it can be confusing illusion.
Solution 1:[1]
From over.ics.list#9.2:
if the initializer list has no elements, the implicit conversion sequence is the identity conversion. [?Example:
void f(int); f( { } ); // OK: identity conversion?—?end example?]
Thus, the conversion from {} to int is an identity conversion, while {} to const std::string& is a user-defined conversion. And since the identity conversion is a better match, the overload corresponding to int will be chosen.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | πάντα ῥεῖ |
