26

I've tried this:

#include <map>

int main() {

  static std::map<int,int> myMap = [](){
    std::map<int,int> myMap;
    return myMap;
  };

}

error:

<stdin>: In function 'int main()':
<stdin>:8:3: error: conversion from 'main()::<lambda()>' to non-scalar type 'std::map<int, int>' requested

And yes, I know that I can create another 'normal' function for it ant it works but lambdas cannot initialize objects in that way.

1 Answer 1

45

Yes, it is indeed possible.

static std::map<int,int> myMap = [](){
  std::map<int,int> myMap;
  return myMap;
}();

Note the () at the end. You are assigning myMap to a lambda, but you really want to assign it to the result of the lambda. You have to call it for that.

Sign up to request clarification or add additional context in comments.

3 Comments

I think you missed the ->std::map<int,int> within the lambda declaration.
@theV0ID, the return type isn't necessary on a lambda if it can be deduced from the return statement (as it can here). (Side note: If the parameter list is empty, as it is here, it is also optional. Thus, this could be written using: static auto myMap = []{ return std::map<int,int>(); }();)
Yes it is. Tested with gcc 4.8, running 5 threads and a static variable within the clousure. [](){ static int i = 0; i += 1; assert(i == 1); }

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.