Consider the following program:
#include <iostream>
void myprint(const char* fmt, ...)
{
std::cout << "1 ";
}
void myprint(const char* fmt, char *x)
{
std::cout << "2 ";
}
int main()
{
const char* s = "c";
myprint("a", s);
myprint("a", "b");
}
It produces different output:
GCC and MSVC: 1 2
clang: 1 1
My question is two-fold:
Why does a string literal bind to a non-const char* even in the presence of -std=c++14? Isn't a string literal const since C++11?
The ellipsis-overload is always ranked lowest. Why does clang select it? (one would think it doesn't allow binding to char* but if I remove the ellipsis overload, it still does - demo)
What's going on and who is right?
Why does a string literal bind to a non-const
char*even in the presence of-std=c++14?
It's a deprecated conversion, which has been officially removed from the standard starting with C++11.
Isn't a string literal
constsince C++11?
No, a string literals is and has always been const.
The ellipsis-overload is always ranked lowest. Why does clang select it?
Because the other one is not valid. There is no conversion from const char* to char*, for the same reason that there is no way to convert a const std::string& to a std::string&.
So overload resolution skips that one and chooses the only remaining overload (which also happens to be valid), and prints 1.
one would think it doesn't allow binding to char* but if I remove the ellipsis overload, it still does
Yes, that is a non-standard extension, just like the gcc one. You should try to compile with -pedantic.
What's going on and who is right?
clang is definitely right. An extension is not allowed to modify the behavior of a well-formed C++ program ([intro.compliance]p8), so gcc and MSVC are wrong to use the second overload, as the standard doesn't support implicit conversions from const char* to char*, and should thus fall back on the first one.
To reiterate, your demo is in compliance with the standard because that program is ill-formed according to the standard (the string conversion) and they issue a diagnostic, and so it doesn't run afoul of the paragraph linked above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With