Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 787
Antoine Morrier Avatar asked Mar 16 '18 21:03

Antoine Morrier


1 Answers

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.

like image 147
P.Carlino Avatar answered Sep 21 '22 05:09

P.Carlino