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

Started by
4 comments, last by EarthBanana 10 years, 8 months ago

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?

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);

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"};
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?

std::array was actually introduced in TR1. But yes, MSVC 2012's coverage of C++11 features is incomplete.


std::array was actually introduced in TR1. But yes, MSVC 2012's coverage of C++11 features is incomplete.

This is useful to know definitely

This topic is closed to new replies.

Advertisement