• Advertisement
Sign in to follow this  

Initializing `static const std::vector<std::wstring>` class data member

This topic is 1713 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have a `static const` vector of strings. I want to initialize it in C++11.

 

My code:

// Settings.h
class Settings
{
	public:
		static const std::vector<std::wstring>	TITLES;
}

//Settings.cpp
const std::vector<std::wstring> Settings::TITLES = {L"Disk", L"System", L"Appearance"};

?

?

I'm getting this error:
 

 

error C2552: 'TITLES' : non-aggregates cannot be initialized with initializer list

 

Intellisense in Visual Studio 2012 reports the error as:

 

 

Error: initialization with '{...}' is not allowed for object of type "const std::vector<std::wstring, std::allocator<std::wstring>>"

 

How do I initialize it correctly?

Share this post


Link to post
Share on other sites
Advertisement
You can either use C++11 (where what you did is perfectly valid) or use the constructor of vector that takes two iterators:
std::wstring titles_init[3] = {L"Disk", L"System", L"Appearance"};
const std::vector<std::wstring> Settings::TITLES(titles_init, titles_init+3);

Share this post


Link to post
Share on other sites

I decided to use "std::array". It doesn't differ from "std::vector" since I won't be (able to) adding (or removing) elements to it.

?

// Settings.h
class Settings
{
	public:
		static const std::array<std::wstring, 3> TITLES;
}

//Settings.cpp
const std::array<std::wstring, 3> Settings::TITLES = {L"Disk", L"System", L"Appearance"};
Edited by hkBattousai

Share this post


Link to post
Share on other sites
Hmmm... I don't understand. std::array was introduced in C++11, but initializing an std::vector the way you did should also work just fine in C++11. Is the issue that Visual C++ has a half-baked implementation of C++11?

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement