Reputation: 230
I have two classes A and B in C++11. There's a static array in class A, which is used in class B. Here is the simplified problem:
// A.h
class A {
public:
static int const a[4];
};
// A.cpp
int const A::a[4] = {1,2,3,4};
// B.h
class B {
public:
void method();
};
// B.cpp
void B::method() {
for(auto const& it:a) {
/* do something */
}
}
It works, but it requires the explicit definition of the array size. I would like to change the content of the array initializer from time to time, at compile time, without the manual redefinition of its size.
What would be an equivalent, but more efficient way to do this?
Upvotes: 2
Views: 487
Reputation: 170239
If it's const
you can't do it. If it's constexpr
however, you can:
class A {
public:
static constexpr int a[] = {1, 2, 3, 4};
};
Just move the initializer into the class definition. Then you can omit the array size completely.
A caveat to note, as pointed out by @SergeBallesta, is that you cannot skip on defining the storage for the array if you odr-use it. Which your example obviously does in the range for loop (it needs pointers to the beginning and past the end). So your cpp file still needs a const int A::a[];
declaration.
In C++17 you can at least make the definition header only thanks to inline variables being added to the language.
Upvotes: 10