Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 425
Lingxi Avatar asked Feb 18 '26 06:02

Lingxi


1 Answers

It's a bug and appears to compile on gcc 5 as shown here.

like image 152
edmz Avatar answered Feb 20 '26 18:02

edmz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!