Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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]'

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading