Search code examples
c++multidimensional-arrayreferencestatic

Can I initialize a static c++ class member which is a multidimensional array with a function?


I have a class that follows as such:


class foo{
  static std::string L[256][256];
  public:
    //rest of class
};

std::string foo:L[256][256];

I would like to initialize L using a function such as the following.

void begin_l(std::string L[256][256]){
  //initialization code
}

I have tried making a function that returns L to accomplish this, but received the error function cannot return array type 'std::string [256][256]'

How could I go about doing this?


Solution

  • You can do it with a directly invoked lambda function :

    #include <iostream>
    #include <array>
    #include <string>
    #include <iomanip>
    
    // add an alias for readability
    using array_2d_of_string_t = std::array<std::array<std::string, 4>, 4>;
    
    class foo 
    {
    public:
        //rest of class
        static array_2d_of_string_t L;
    };
    
    // initialize static variables with a directly
    // invoked lambda function. The lambda function will be a nameless
    // function so it can only be used to initialize this variable.
    array_2d_of_string_t foo::L = []
    {
        std::size_t count{ 0ul };
        array_2d_of_string_t values{};
    
        // loop over all rows in the 2d array
        for (auto& row : values)
        {
            // loop over all the values in the array and assign a value
            for (auto& value : row)
            {
                value = std::to_string(count++);
            }
        }
    
        return values;
    }();
    
    int main()
    {
        for (auto& row : foo::L)
        {
            for (auto& value : row)
            {
                std::cout << std::quoted(value) << " ";
            }
            std::cout << "\n";
        }
    
        return 0;
    }