带有 GCC 和 clang 的 constexpr char 数组
constexpr char array with GCC and clang
考虑以下代码:
#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]>();
}
它用 clang 编译得很好,而 GCC 给出了以下错误消息:
in constexpr expansion of 'const_string((* & str)).const_string::operator[](0ul)'
error: '(const char*)(& str)' is not a constant expression
但是,如果我将 Print<const_string(str)[0]>();
更改为 Print<const_string("Hello World")[0]>();
。 clang 和 GCC 都可以正常编译。
这是怎么回事?根据标准,哪个编译器是正确的?
考虑以下代码:
#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]>();
}
它用 clang 编译得很好,而 GCC 给出了以下错误消息:
in constexpr expansion of 'const_string((* & str)).const_string::operator[](0ul)'
error: '(const char*)(& str)' is not a constant expression
但是,如果我将 Print<const_string(str)[0]>();
更改为 Print<const_string("Hello World")[0]>();
。 clang 和 GCC 都可以正常编译。
这是怎么回事?根据标准,哪个编译器是正确的?