考虑以下代码:
#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 编译都很好。
这是怎么回事?根据标准,哪个编译器是正确的?
最佳答案
关于c++ - 带有 GCC 和 clang 的 constexpr char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29866347/