rsk82
rsk82

Reputation: 29377

is it possible to initialize static variable with lambda?

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.

Upvotes: 25

Views: 10435

Answers (1)

ipc
ipc

Reputation: 8143

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.

Upvotes: 43

Related Questions