The following program displays 1. It seems completely unnatural to me. Do you know the reason behind this decision? How do you circumvent this problem, especially if you want to provide a constructor which can take both const char (&s)[n]
and const char* s
.
template <int n>
int f(const char (&s)[n]) {
return 0;
}
int f(const char* s) {
return 1;
}
int main() {
std::cout << f("hello") << std::endl;
return 0;
}
It's too bad, because you end up defining a constructor for string class with : const char*
. Using that, the program must compute the length of the C-string at run-time which is a waste of time. On my own class, it takes 3ns
to initialize a string with const char (&s)[n]
and 20ns
to initialize a string with const char*
.
PS: This question is not the same as "What is array decaying?". First, we are in C++ here where the standard says:
An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to an rvalue of type “pointer to T.
which is by the way very fuzzy (can is not very precise). All I want to know is the rationale behind it.