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.
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.
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.
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.
The lambda function can take many arguments but can return only one expression.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With