【问题标题】:constexpr char array with GCC and clang带有 GCC 和 clang 的 constexpr char 数组
【发布时间】:2015-07-04 04:06:18
【问题描述】:

考虑以下代码:

#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&lt;const_string(str)[0]&gt;(); 更改为 Print&lt;const_string("Hello World")[0]&gt;();。 clang 和 GCC 都可以正常编译。

这里发生了什么?根据标准,哪个编译器是正确的?

【问题讨论】:

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


【解决方案1】:

它是一个bug,似乎可以在 gcc 5 上编译,如 here 所示。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-29
    • 1970-01-01
    • 2014-02-27
    • 1970-01-01
    • 2019-05-03
    • 1970-01-01
    • 2023-03-15
    相关资源
    最近更新 更多