3

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?

1
  • 1
    Compiles in head (and the most recent version, 5.1) Commented Apr 25, 2015 at 14:29

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.