Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to initialize static variable with lambda?

Tags:

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.

like image 428
rsk82 Avatar asked Mar 22 '13 23:03

rsk82


People also ask

Can static variables be initialized?

Static variables are initialized only once. Compiler persist the variable till the end of the program. Static variable can be defined inside or outside the function.

Are lambda functions static?

A lambda or anonymous method may have a static modifier. The static modifier indicates that the lambda or anonymous method is a static anonymous function. A static anonymous function cannot capture state from the enclosing scope.

Is static variable initialization necessary?

Initialization of Instance variables But if you declare an instance variable static and final Java compiler will not initialize it in the default constructor therefore, it is mandatory to initialize static and final variables.

Can Lambda return value?

The lambda function can take many arguments but can return only one expression.


1 Answers

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.

like image 106
ipc Avatar answered Sep 18 '22 02:09

ipc