Initialize a static const list of strings

16,912

Solution 1

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?

Solution 2

You can't initialize a static data member inside of the class. What you can do, however, is declare the static data member like this:

class myClass{
    static const std::list<std::string> myList;
}

inside your class in the header file, and then initialize it like this, in one of the implementation files:

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

Hope this helps.

Solution 3

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.

Share:
16,912
David Pham
Author by

David Pham

Updated on June 04, 2022

Comments

  • David Pham
    David Pham almost 2 years

    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.