Jump to content

  • Log In with Google      Sign In   
  • Create Account


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


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
5 replies to this topic

#1 hkBattousai   Members   -  Reputation: 153

Like
0Likes
Like

Posted 17 August 2013 - 01:51 AM

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?



Sponsor:

#2 Álvaro   Crossbones+   -  Reputation: 12383

Like
1Likes
Like

Posted 17 August 2013 - 04:24 AM

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


#3 hkBattousai   Members   -  Reputation: 153

Like
2Likes
Like

Posted 17 August 2013 - 04:38 AM

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, 17 August 2013 - 04:40 AM.


#4 Álvaro   Crossbones+   -  Reputation: 12383

Like
0Likes
Like

Posted 17 August 2013 - 04:21 PM

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?

#5 SiCrane   Moderators   -  Reputation: 9492

Like
3Likes
Like

Posted 17 August 2013 - 04:27 PM

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



#6 EarthBanana   Members   -  Reputation: 844

Like
0Likes
Like

Posted 17 August 2013 - 06:34 PM


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






Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS