I wanted to initialize a constexpr member variable using a constexpr member function but it didn't compile. It was OK when I moved the function out of the class. Why does it happen? Is there any way to use class member constexpr functions to initialize member constexpr variables?
I'm using Apple LLVM version 8.0.0 (clang-800.0.38).
Thanks for any help.
constexpr static int Add_Ext(int a, int b) { return a + b; }
class Foo
{
public:
constexpr static int Add_InClass(int a, int b) { return a + b; }
// This is OK.
constexpr static int kConstantX = Add_Ext(1, 2);
// This results in a compile error.
constexpr static int kConstantY = Add_InClass(1, 2);
};
clang error message:
Constexpr variable 'kConstantY' must be initialized by a constant expression
const can only be used with non-static member functions whereas constexpr can be used with member and non-member functions, even with constructors but with condition that argument and return type must be of literal types.
A constexpr function is one whose return value is computable at compile time when consuming code requires it. Consuming code requires the return value at compile time to initialize a constexpr variable, or to provide a non-type template argument.
Both const and constexpr mean that their values can't be changed after their initialization. So for example: const int x1=10; constexpr int x2=10; x1=20; // ERROR. Variable 'x1' can't be changed.
Absolutely not. Not even close. Apart from the fact your macro is an int and your constexpr unsigned is an unsigned , there are important differences and macros only have one advantage.
From CWG-1255 and CWG-1626
The Standard should make clear that a
constexpr
member function cannot be used in a constant expression until its class is complete.
It seems like your code is intentionally unacceptable. However, the standard should make it more clear in that matter.
Is there any way to use class member constexpr functions to initialize member constexpr variables?
w.r.t. those DRs, No. You can move it to outside or to another class instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With