0

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; } { }
}
2
  • I suppose you can always call a (freestanding or static) function that returns a map that depends on the run-time value of i? You won't be able to do that with literals, or (even recursive ) constexpressions, or (even recursive) templates because i is not known at compile time. The problem is the overhead in passing a map by value with pre-move standards/implementations. Commented Jan 14, 2021 at 10:36
  • 1
    You can use a function or a lambda expression. Commented Jan 14, 2021 at 10:48

1 Answer 1

3

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; 
    }()) {}
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.