【问题标题】:Static constexpr: why does it need to be templated?静态 constexpr:为什么需要模板化?
【发布时间】:2018-03-16 21:45:40
【问题描述】:

我有两个结构ab

struct a {
    static constexpr int f() {
        return 1;
    }

    static constexpr int c = f();
};

template<int I>
struct b {
    static constexpr int f() {
        return I;
    }

    static constexpr int c = f();
};

a 显然不起作用,因为f 被认为未在此处定义。但是为什么b 是有效的呢?

【问题讨论】:

  • 为什么a::f 被认为是不完整的?
  • @NicolBolas 不完整但未定义,请参阅:stackoverflow.com/questions/16493652/…
  • 这很有趣。我认为答案必须是模板成员都是首先定义的,然后才实例化。但是找到相关的标准报价被证明是棘手的,整个事情带来了其他问题......
  • 这是核心问题 2335 的另一个变体。
  • 可以在c++17中添加内联帮助吗?

标签: c++ c++14 constexpr


【解决方案1】:

对此我不确定,但我认为编译器会以这种方式扩展该模板(如果 int I 为 1):

struct b {
    static constexpr int f();
    static const int c;
};

constexpr int b::f(){
    return 1;
};

const int b::c = f();

所以它可以编译,因为 b::f 的调用是在它的声明之后完成的

事实上,如果你以这种方式声明 a 它将编译:

struct a {
    static constexpr int f();
    static const int c;
};

constexpr int a::f(){
    return 1;
};

const int a::c = f();

所以答案是在编译期间编译器将 b::c 评估为 const 值而不是 constexpr。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-15
    • 2017-09-02
    • 1970-01-01
    • 2018-07-02
    • 1970-01-01
    • 1970-01-01
    • 2012-09-08
    相关资源
    最近更新 更多