JamesR
JamesR

Reputation: 363

How should one initialise this member vector in C++11-style?

I have a class with a member variable which is a std::vector<double>. I would like to initialise this in the initialisation list of the class. I've tried the following code

MyClass::MyClass()
  : m_myMemberVector( { 1.0, 2.0 } )
{...}

but the compiler interprets this as the (itBegin, itEnd) constructor for std::vector. I've seen this question error: ‘double’ is not a class, struct, or union type, which points out the input iterator issue but doesn't provide a solution.

I have a working implementation using BOOST in the body of the constructor, but I'd rather do this in the initialisation list if possible. Is there any elegant way to construct a vector containing two doubles using C++11-style initialisation?

Upvotes: 1

Views: 184

Answers (2)

JamesR
JamesR

Reputation: 363

The simple solution was correct: C++11 wasn't properly enabled. I saw compiler output of the form

MyClass.cxx:5:5: warning: extended initializer lists only available with -std=c++11 or -std=gnu++11 [enabled by default]

and assumed this meant that C++11 support would be "enabled by default"! Recompiling with the explicit use of -std=c++11 worked as expected.

There was an answer suggesting this, which I wanted to accept, but it seems to have been deleted. Thanks for all the comments which made this point.

Upvotes: 2

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275405

std::initializer_list<double>{ 1.0, 2.0 } instead of { 1.0, 2.0 } might work, as might removing the () around { 1.0, 2.0 }.

Odds are this is a bug in your compiler, so making things more explicit may help.

Another possibility is that m_myMemberVector is not a std::vector<double> actually, or that your standard library you are using is not C++11 enabled.

Upvotes: 2

Related Questions