Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize a static const list of strings

I need to initialize a static const std::list<std::string> in my .h. But, how do I do ?

class myClass {
    static const std::list<std::string> myList = {"a", "b", "c"};
}

Thanks.

like image 774
David Pham Avatar asked Nov 22 '25 06:11

David Pham


2 Answers

How do I initialize a static const std::list in my .h?

No you can't directly do that.

To initialize a const static data member inside the class definition, it has to be of integral (or enumeration) type; that as well if such object only appears in the places of an integral-constant expression. For more details, plese refer C++11 standard in the following places.

$9.4.2 Static data members and
$3.2 One Definition rule

But, you MAY be able to do something like this: How can you define const static std::string in header file?

like image 141
smRaj Avatar answered Nov 23 '25 20:11

smRaj


With c++11 you could use the "initialize of first call" idiom as suggested on the answer pointed by @smRaj:

class myClass {
 public:
  // The idiomatic way:
  static std::list<std::string>& myList() {
    // This line will execute only on the first execution of this function:
    static std::list<std::string> str_list = {"a", "b", "c"};
    return str_list;
  }

  // The shorter way (for const attributes):
  static const std::list<std::string> myList2() { return {"a", "b", "c"}; }
};

And then access it as you normally would but adding a () after it:

int main() {
  for(std::string s : myClass::myList())
    std::cout << s << std::endl;
}

output:

a
b
c

I hope it helps.

like image 36
VinGarcia Avatar answered Nov 23 '25 18:11

VinGarcia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!