Reputation: 79
I tried to understand how to use constexpr from different sources. But I have a problem that I want to convert the program below to use constexpr instead of const. This program is template of my main program.
class B;
class A{
public:
constexpr A(int){}
const static B& obj;
};
class B:A{
public:
constexpr B(int x):A(x){}
const static B& obj;
};
const B& A::obj=B(10);
const B& B::obj=B(20);
In last line I want to use constexpr to ensure that this obj variable is present at compile time and thus reduce my code size and optimize but according to standards constexpr can't be used. And it gives error about multiple declarations. And if I change the const in class A then initialization is must.I want to use obj variable in constexpr function and since obj is not present in compile time error occure. I am asking how can I solve the problem because if this cannot be done then probably the optimization of code is affected by 15% thats really huge.
Upvotes: 2
Views: 161
Reputation: 26800
As constexpr
applies the const-ness to the object defined, you can use constexpr
before const
in the last line or the last two lines (if that's what you really want) like this.
constexpr const B& A::obj=B(10);
constexpr const B& B::obj=B(20);
This works. See compiled demo here.
Upvotes: 1