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.
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With