Reputation: 1704
I was wondering the other day whether it is possible in C++ (any standard) to initialize a map in an initializer list of a constructor with a loop or a more complex procedure than literals such that I can make it a const
member variable?
class MyClass {
public:
const int myInt;
const std::unordered_map<int, int> map;
MyClass(int i) : myInt(i), /* initialize map like: for(int i = 0; i < myInt; ++i) { map[i] = whatever; } { }
}
Upvotes: 0
Views: 328
Reputation: 32063
You could use a lambda
function inside constructor initializer list. Like so:
class MyClass {
public:
const int myInt;
const std::unordered_map<int, int> umap;
MyClass(int i) : myInt(i), umap( [i]() -> decltype(umap) {
std::unordered_map<int, int> tu;
for(int j=0; j<i; j++)
tu[j]=j;
return tu;
}()) {}
};
Upvotes: 3