Reputation: 161
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.
Upvotes: 3
Views: 23091
Reputation: 735
The class static variables can be declared in the header but must be defined in an implementation file. This is because there can be only one instance of a static variable and the compiler can't decide in which generated object file to put it so you have to make the decision by defining the variable in an implementation file.
To keep the definition of a static value with the declaration in C++11 a nested static structure can be used. In this case the static member is a structure and has to be defined in a .cpp file, but the values are in the header.
class myClass
{
public:
static struct _Globals {
const std::list<std::string> myList = {"a", "b", "c"}
} g;
};
Instead of initializing individual members the whole static structure is initialized in .cpp:
myClass::_Globals myClass::g;
The values are accessed with
myClass::g.myList;
Some more information about static variables is in this answer about static strings.
Upvotes: 0
Reputation: 1195
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.
Upvotes: 3
Reputation: 1306
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?
Upvotes: 4
Reputation: 1322
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.
Upvotes: 2
Reputation: 607
Maybe something like this (I'd better reconsider the architecture :))
static std::string tmp[] = { "a", "b", "c" };
static std::list<std::string> myList(tmp, tmp + 2);
Upvotes: 0