Suppose you want to have a static array of pre-defined values/objects (const or non-const) associated with a class. Possible options are to use std:vector
,
I personally like your constexpr static int my_array[] = {MyClass{1, 2, 3}, MyClass{1, 2, 3}};
I don't think you should shy away from that if a C-style array meets your needs.
If you really want to use std::vector
though you could use static const std::vector
. So your .cpp
file would have this at the top:
namespace{
MyClass A{1, 2, 3}, B{1, 2, 3}, C{1, 2, 3};
}
const std::vector MyClass::vec_pre{&A, &B, &C};
EDIT after DarkMatter's comments:
After reading your comments, it looks like there could be some maintainability hazard to my method. It could still be accomplished like this in your .cpp
:
namespace{
MyClass temp[]{MyClass{1, 2, 3}, MyClass{1, 2, 3}, MyClass{1, 2, 3}};
const MyClass* pTemp[]{&temp[0], &temp[1], &temp[2]};
}
const std::vector MyClass::vec_pre{begin(pTemp), end{pTemp}};
You could also remove the duplication of entry maintainability problem by creating a macro to do that for you.