Antoine Morrier
Antoine Morrier

Reputation: 4076

Static constexpr: why does it need to be templated?

I have two structures a and b:

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 is obviously not working because f is considered to be not defined here. But why the hell b is valid?

Upvotes: 16

Views: 272

Answers (1)

P.Carlino
P.Carlino

Reputation: 681

I'm not sure about that but i think that the compiler will expand that template in this way (in the case that int I would be 1):

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

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

const int b::c = f();

So it compiles because the call of b::f is done after its declaration

infact if you declare a in this way it will compile:

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

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

const int a::c = f();

So the answer is that during compiling the compiler evaluates b::c as a const value and not constexpr.

Upvotes: 1

Related Questions