Initializing a constexpr member variable using the constexpr member function

I wanted to initialize the constexpr member variable using the constexpr member function, but it did not compile. This was normal when I moved a function from a class. Why is this happening? Is there a way to use constexpr member functions to initialize constexpr member variables?

I am 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
+4
source share
2 answers

From CWG-1255 and CWG-1626

, - constexpr .

, . .

- constexpr - constexpr?

w.r.t. DR, . .

0

Danh. WG, , , - constexpr, .

// This works (it doesn't if you make it as a non-template class).
template <typename T>
class TemplateFoo
{
public:
    constexpr static T Add_InClass(T a, T b) { return a + b; }
    constexpr static T kConstantY = Add_InClass(1, 2);

};

// Even such a meaningless template works too. 
template <typename T>
class TemplateBar
{
public:
    constexpr static int Add_InClass(int a, int b) { return a + b; }
    constexpr static int kConstantY = Add_InClass(1, 2);

};

// So, this would be a (dirty but) useful workaround 
// when you don't want to use the class as a template.
// Any type could be used as the template argument, which has no meaning.
using Bar = TemplateBar<char>;
0

Source: https://habr.com/ru/post/1664028/


All Articles