Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialization of constexpr member variable using constexpr member function [duplicate]

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
like image 428
Poinsettia Avatar asked Dec 17 '16 05:12

Poinsettia


People also ask

Can a member function be constexpr?

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.

What is constexpr function in C++?

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.

Can constexpr variable be changed?

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.

Is constexpr can be used with #define macros?

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.


1 Answers

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.

like image 106
Danh Avatar answered Oct 31 '22 19:10

Danh