繁体   English   中英

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

[英]Static constexpr: why does it need to be templated?

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

我不确定,但我认为编译器会以这种方式扩展该模板(在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的调用是在声明之后完成的

infact如果你以这种方式声明它将编译:

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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM