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?
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;
};
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;
};
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