c++ - 带有 GCC 和 clang 的 constexpr char 数组

标签 c++ arrays c++11 language-lawyer constexpr

考虑以下代码:

#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 编译都很好。

这是怎么回事?根据标准,哪个编译器是正确的?

最佳答案

这是一个bug并且似乎在 gcc 5 上编译,如图所示 here .

关于c++ - 带有 GCC 和 clang 的 constexpr char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29866347/

相关文章:

c++ - 计算表示有符号整数所需的最小字节数

c++ - 如何打印unicode字符的位表示

java - 尝试提示我的数组输入 10 个数字来执行模式

javascript - 它给出 NaN 而不是数组的内容

c++ - 为什么在创建内置数组的模板函数中不允许使用 auto?

c++ - OpenCV VideoWriters 的输出目录有问题

c++ - 在 win32 API 中将 int 转换为字符串

arrays - 在 swift 中向数组添加函数

c++ - 带有整数参数的 std::pow,与整数类型进行比较

c++ - new char 实际上是否保证类类型的对齐内存?