Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare static constexpr variable in C++?

I have a Foo class that includes an array and a static constexpr variable. As a general convention, I want to write public and private variables respectively. But, compiler error occurs 's_array_size' was not declared in this scope when I compile the header code below.

#ifndef FOO_H
#define FOO_H
#include <array>
#include <cstddef>

class Foo
{
public:
    Foo();
    std::array<int, s_array_size> m_array;
private:
    constexpr static size_t s_array_size;
}

#endif

I can make s_array_size public or I can move the private section above the public section to solve the problem. However, I don't like these solutions as I want two sections public and private respectively. Is there any way to declare a constexpr static variable inside a class?

like image 997
unique Avatar asked Feb 11 '26 03:02

unique


2 Answers

Move your constant upward, it must be known before you declare your array

https://godbolt.org/z/MzPh3Ps3W

#include <array>
#include <cstddef>

class Foo
{
private:
    static constexpr std::size_t s_array_size{4ul};    
public:
    Foo();
    std::array<int, s_array_size> m_array;
};
like image 102
Pepijn Kramer Avatar answered Feb 15 '26 19:02

Pepijn Kramer


The problem is not to declare a constexpr static member. You can do that:

class Foo
{
private:
    constexpr static size_t s_array_size = 0;
};

It must have an initializer though.

To use the member as size of an array, swap the two members:

class Foo
{
private:
    constexpr static size_t s_array_size = 0;
public:
    std::array<int, s_array_size> m_array;
};
like image 35
463035818_is_not_a_number Avatar answered Feb 15 '26 17:02

463035818_is_not_a_number



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!