Constexpr char array with GCC and clang
Consider the following code:
#include <cstddef>
#include <iostream>
#include <stdexcept>
class const_string {
public:
template <std::size_t sz>
constexpr const_string(const char (&str)[sz]): p_(str) {}
constexpr char operator[](std::size_t i) const { return p_[i]; }
private:
const char* p_;
};
template <char c>
void Print() { std::cout << c << '\n'; }
int main() {
constexpr char str[] = "Hello World";
Print<const_string(str)[0]>();
}
It compiles with clang and GCC gives the following error message:
in constexpr expansion of 'const_string((* & str)).const_string::operator[](0ul)'
error: '(const char*)(& str)' is not a constant expression
However, if I change Print<const_string(str)[0]>();
to Print<const_string("Hello World")[0]>();
. Both clang and GCC compile.
What's going on here? Which compiler is correct according to the standard?
+3
source to share