静态constexpr:为什么需要模板化?

时间:2018-03-16 21:45:41

标签: c++ c++14 constexpr

我有两个结构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有效?

1 个答案:

答案 0 :(得分:1)

我不确定,但我认为编译器会以这种方式扩展该模板(在int为1的情况下):

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

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

const int b::c = f();

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

因为如果以这种方式声明它将编译:

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。