samedi 25 avril 2015

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 fine with clang, while 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 fine.

What is going on here? Which compiler is correct according to the standard?

Aucun commentaire:

Enregistrer un commentaire