C++11 ä¾é¡ã§ãããlambda
çããããã«ã¡ã¯
ãå
æ°ã§ãããç§ã¯å
æ°ã§ãã
ãã¦ãä»æ¥ã¯lambdaå¼ã«ã¤ãã¦ãããã¨æãã¾ãã
C++11ã§ã¯lambdaå¼ãå°å
¥ããã¾ãããç¡åé¢æ°ãã©ã ãå¼ãã¯ãã¼ã¸ã£ã¨ãå¼ã°ããããã¦ãã¾ãããä½ãã便å©ãªãããªã®ã§ãã
ãã¦ãæ©éå®è¡ãã¦ã¿ã¾ãããã
ã½ã¼ã¹ã³ã¼ã
#include <iostream> using namespace std; template<typename Function> void execFunction(Function &function){ function(); } int main(void){ //é常ã®Hello World []{ cout << "Hello World" <<endl; }(); //functionã¨ãã¦ä¿æ+å®è¡ auto function = []{ cout << "Hello World" <<endl; }; function(); //å¼æ°ã«ã©ã ãå¼ã渡ãã execFunction(function); //å¤æ°ã¨ãã¦å®è¡ int a = 0; [&]{ a += 1;}(); cout << a << endl; //=ã使ãã¨ã¹ã³ã¼ãå ã®å¤æ°ãã®ã¾ã¾ãå©ç¨ã§ããã [=]{ int b = a + a; cout << b << endl;}(); //å¼æ°ãæå®ããã©ã ãå¼ãå®è¡ã§ãã [](int a,int b){cout << a + b << endl;}(1,2); cout << [](int a,int b)->int{return a + b;}(1,2) << endl; return 0; }
Result
Hello World Hello World Hello World 1 2 3 3
説æ
//é常ã®Hello World []{ cout << "Hello World" <<endl; }();
åç´ãªHelloWorldãåºåãã¾ãã
auto function = []{ cout << "Hello World" <<endl; }; function();
å¤æ°ã«ã©ã ãå¼ãä¿åãããããå®è¡ãã¦ãã¾ãã
int a = 0; [&]{ a += 1;}(); cout << a << endl;
ãã¼ã«ã«å¤æ°ã使ãæ¹æ³ã§ãã&ã¨ããã¨ã©ã®ãã¼ã«ã«å¤æ°ãå©ç¨ãããã¨ãã§ãã¾ãã
//å¼æ°ãæå®ããã©ã ãå¼ãå®è¡ã§ãã [](int a,int b){cout << a + b << endl;}(1,2);
å¼æ°ãå®è¡ããã¨ãã¯[]ã®å¾ã«(å¼æ°)ãæ¸ãã¾ãã
cout << [](int a,int b)->int{return a + b;}(1,2) << endl;
æ»ãå¤ãåãæã§ã->intã§åãè¨å®ãã¦ãã¾ãã
ãã¾ã使ãã°ä¾¿å©ããã§ããã«ã¼ãã®ä¸ãå°ãå¤ãããæã¨ãç¹ã«