In Visual C++ 2017 (with /std:c++14
or with /std:c++17
), the following code works:
void TakePtr(char*); // const or not
int main()
{
TakePtr(char{});
TakePtr(char());
}
I don't understand why it works.
Apparently, the following would also work (as expected):
void TakeChar(char);
TakeChar(char{});
TakeChar(char());
How does the compiler deduce (or convert) the type char
to char*
, when char{}
or char()
is used as an argument?
Now, if I have both char
and char*
overloads, it works without any error/warning about ambiguity:
void TakePtr(char*);
void TakePtr(char);
TakePtr(char{}); // Chooses 'char'
TakePtr(char()); // Chooses 'char'
Why is the compiler okay with char{}
for TakePtr(char*)
?
And why doesn't it give a warning/error when choosing the better version? Such behavior is bound to break existing code.
For sure, the compiler isn't happy with:
void TakePtr(char*);
char c{};
TakePtr(c);
char()
constructs a temporary(char)0
which is convertible to any integral0
which is accepted as null pointer. I tested in godbolt, and I believe I'm right: Compiler Explorer. – Olympiasxor ecx, ecx; call void TakePtr(char *)
. – Froniavoid TakePtr(char) = delete;
– JookTakePtr(char{8})
fails,TakePtr(char{0})
doesn't. – StomatalTakePtr(char
) or made not-present by explicitdelete
, it raises an error. When only one (char*
) is present it takes it. – Stomatal