Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

most vexing parse prevents in-class initializing a std::vector<int>

C++11 allows in-class initialization:

struct Foo{
    std::vector<std::string> v{3}; // vector of 3 empty strings
};

If we wanted to initialize in-class a vector of ints, we would get something else:

struct Foo{
    std::vector<int> v{3}; // vector of one element with value 3
};

This issue seems to be a limitation of the language, as discussed in previous questions. However, if this were not an in-class initialization, we would be able to use parentheses instead of braces, and get the desired result:

std::vector<int> v(3); // vector of three zeros

However, we cannot do this in a class because of most vexing parse:

struct Foo{
    std::vector<int> v(3); // most vexing parse; doesn't compile
};

Of course, it's debatable whether the code above is good design practice, since we can easily just move what we're trying to do into a constructor. But temporarily putting that aside, is there a way to perform the desired initialization, as closely as possible to the first std::string example, which works with no problem?

like image 851
xdavidliu Avatar asked Feb 10 '18 16:02

xdavidliu


1 Answers

Default member initializers work with = as well. So

struct Foo{
    std::vector<int> v = std::vector<int>(3);
};

Will do it. Though obviously, a major caveat is the fact that we are repeating the type name here.

We can alleviate it somewhat with decltype:

struct Foo{
    std::vector<int> v = decltype(v)(3);
};

But that still has us naming things twice.

like image 66
StoryTeller - Unslander Monica Avatar answered Oct 29 '22 18:10

StoryTeller - Unslander Monica