1

How can I initialise a static member variable "dynamically"?

For instance, I declare this variable in the header file of a class:

class MyPermutation {
    static std::array<std::vector<uint8_t>,2> permutation_list;
};

And I want it to have the following values:

permutation_list[0] = std::vector<uint8_t>{0};
permutation_list[1] = std::vector<uint8_t>{};
for ( uint8_t i = 0; i < 8; i++ )
    permutation_list[1].push_back( 1<<i );

Where should I put the above code?

Andreas
  • 7,470
  • 10
  • 51
  • 73
  • 1
    Maybe that can help: http://stackoverflow.com/questions/1197106/static-constructors-in-c-need-to-initialize-private-static-objects – codeling Oct 03 '13 at 07:57

1 Answers1

3

this is usually done by a function that is called to initialize the static variable:

std::array<std::vector<uint8_t>,2> MyPermutation::permutation_list = someFunctionThatBuildsTheInitialValues();

Or, since C++11, it can be a lambda:

std::array<std::vector<uint8_t>,2> MyPermutation::permutation_list = 
  []() -> std::array<std::vector<uint8_t>,2> {
    std::array<std::vector<uint8_t>,2> the_list;
    the_list[0] = std::vector<uint8_t>{0};
    the_list[1] = std::vector<uint8_t>{};
    for ( uint8_t i = 0; i < 8; i++ )
      the_list[1].push_back( 1<<i );
    /* ... */
    return the_list;
  }();
Arne Mertz
  • 24,171
  • 3
  • 51
  • 90