mardi 26 juillet 2016

Compile time evaluation of literal type members

Suppose we have two literal types A and B defined as below. Literal type B can be initialized at compile time from literal type A. A third non-literal type C contains the literal type B as a member. The question is, if we initialize a at compile time and pass it to C's constructor, is b initialized at compile time as well? Since C is a non-literal type, its member v is not initialized at compile time. However, is there a partial compile time initialization happening for b? If that is the case, would a constexpr member function such as f evaluate at compile time if used inside C? Obviously we can not use such function at compile time outside the struct C, since we can not declare C's objects to be constexpr.

struct A {
    constexpr A(int num): num{num} {}
    int num;
};

struct B {
    constexpr B(A a): num{a.num} {}
    int num;
};

struct C {
    C(A a, std::initializer_list<int> data): b{a}, v{data} {}

    constexpr int f() const {
        return b.num + 42;
    }

    B b;
    std::vector<int> v;
};

int main() {
     constexpr A a {4};
     C c {a, {5}};
}

Aucun commentaire:

Enregistrer un commentaire