4. Using the library

ΥŪϦ˥饤֥δŪʵǽҲ𤹤뤳ȤǤ롣 㳰̤ʾˤ󤢤뤬ˤĤƤϸΥˤޤ魯Ȥˤ롣

4.1. Introductory Examples

ΥǤϡSTL 르ꥺθƽФˤ롢BLL Φ˼δŪ򼨤 ĤñʼϤơȯŸƤ ޤƥ( 㤨 list ) Ǥ 1 ˽Ƥߤ롣

list<int> v(10);
for_each(v.begin(), v.end(), _1 = 1);
_1 = 1 ˥ե󥯥Ѥơv γǤ 1 Ƥ롣 [1]

ˡݥ󥿤ΥƥʤΥݥ󥿤Υƥ v Ǥؤ褦ˤ롣

vector<int*> vp(10); 
transform(v.begin(), v.end(), vp.begin(), &_1);
&_1ȤϡvΤ줾ǤΥɥ쥹ؿ֥Ȥ롣 ơΥɥ쥹бvpǤ롣

Υɤ v ǤͤѲ롣 줾ǤФơؿfoo ƤФ롣 fooˤϡǤͤȤϤ졢η̤ϰȤϤ줿Ǥ롣

int foo(int);
for_each(v.begin(), v.end(), _1 = bind(foo, _1));

ˡvp ǤΥȤԤ

sort(vp.begin(), vp.end(), *_1 > *_2);
sortθƽФǤϡǤݥ󥿤λؤƤι߽ǥȤ롣

Ǹˡ for_each θƽФǤϡȤ줿 vp ǤλؤƤԶڤǽϤ롣

for_each(vp.begin(), vp.end(), cout << *_1 << '\n');
˼ʬ̾μ( ˼Ǥʤ )Τ¨¤ɾ뤳ȤդʤФʤʤ ʤȡͽʤ̤ƳƤޤ 㤨С򼡤Τ褦˽񴹤Ƥߤȡ ʬcout << << '\n' ¨¤ɾƤޤ η̡ĤβԤȤ³ vp ǤϤƤޤ
for_each(vp.begin(), vp.end(), cout << '\n' << *_1);
BLL Ǥϴؿ constant ȴؿ var 󶡤Ƥꡢ줾ѿ˼ؤѴ롣 δؿѤ뤳Ȥˤꡢʬ¨¤ɾƤޤȤɻߤǤ롣
for_each(vp.begin(), vp.end(), cout << constant('\n') << *_1);
δؿ Section 5.5 ǤܤҤ롣

4.2. Parameter and return types of lambda functors

˥ե󥯥θƽФδ֤ϡ°ϥץ졼ۥȤݲƤ롣 ץ졼ۥϼ°ηˤϱƶͿʤ Ūˤϡݲ줿˼ C++ ͭʼǤ뤫ꡢ˴ؿϤʤ뷿ΰȤʤäƤƤ֤ȤǤ롣 㤨С _1 + _2 ϡ˥ե󥯥롣 Υե󥯥Ϥʤ뷿 A B ĤΥ֥ Ȥȶ˸ƽФȤǤ롣ηˤ operator+(A,B) ƤФ褤(ơBLL α黻Ҥ֤̤ͤǤ Ф褤ܤϰʲ򸫤衣)

C++ ˤϼη礻ᥫ˥ब¸ߤʤ ޤˤεǽ C++ Φ˼μˤ϶ˤƽǤ롣 äơBLL 饹νѤƦ˴ؿ֤ͤηäȤʣʷƥ񤷤Ƥ롣 οƥϡڥɤȤ߹߷Ǥ뼰ȡڥɤɸ饤֥η򥪥ڥɤȤ뼰Ǥ뼰򰷤 ¿Υ桼⡢ä˥桼α黻Ҥ̾δ˽äƤСƱͤбƤ롣

ʤ顢֤ͤηǤʤ礬¸ߤ롣 㤨СΤ褦򤷤Ȥȡ

C operator+(A, B);
Φ˥ե󥯥θƽФϡ֤ͤηǤʤ˼Ԥ롣
A a; B b; (_1 + _2)(a, b);

褹ˤĤذƤ롣 ܤϡBLL ηƥȼηб뤿˳ĥ뤳Ȥ (ܤ Section 6 򸫤) ܤˡϼΤ褦̤ʦ˼ ret Ѥ뤳ȤǤ롣

A a; B b; ret<C>(_1 + _2)(a, b);
Φ˼Ϸƥäơ֤ͤηꤹ롣 (ܤ Section 5.4 򸫤)

bind ˴ؤƤϡ֤ͤηϥƥץ졼ȰȤƼΤ褦˻ꤹ 뤳ȤǤ롣

bind<int>(foo, _1, _2);

4.3. About actual arguments to lambda functors

Ūʼ°¤ϡ°ˤ const ʱͤǤʤ 㤨С

int i = 1; int j = 2; 
(_1 + _2)(i, j); // ok
(_1 + _2)(1, 2); // error (!)
Ǥ롣 ¤ϤۤɰΤǤϤʤ ˥ե󥯥ϤƤξ硢STL Υ르ꥺǸƽФ뤿ᡢϥƥ졼򻲾ȳΤǤꡢȳ֤ͤȤϤۤȤɤʤǤ롣 ơ֤ͤ褦ʾˤϡSection 5.9.2ǽҤ٤褦ذƤ롣

4.4. Storing bound arguments in lambda functions

ǥեȤưǤϡ«줿 const ʰŪʥԡ˥ե󥯥˳Ǽ롣 Ĥޤꡢ«줿ͤϡ˴ؿ˸ꤵ졢ġ˴ؿ֥ȤΥ饤եδ֤Ǥ³ȤȤǤ롣 㤨С

int i = 1;
(_1 + i)(i = 2);
ǸιԤμͤ 4 ǤϤʤ3 Ǥ롣 ȡ˼ _1 + i lambda x.x+iǤϤʤ lambda x.x+1Ȥ˴ؿ롣

˽Ҥ٤褦ˡϤޤǥǥեȤưǤäơ㳰⤢롣 Τʵ§ϼΤ褦ˤʤ롣

  • ץޤref cref Υå[ref]Ѥ뤳ȤˤꡢǼΥᥫ˥뤳ȤǤ롣 ref crefǥåפ뤳Ȥˤꡢ򤽤줾컲ȤȤơconst ؤλȤȤƳǼ褦˻ꤹ뤳ȤǤ롣 㤨Сѿ i ref ǥåפƽľС lambda x.x+iȤ˼ǸιԤμͤ 4 Ȥʤ롣

    i = 1;
    (_1 + ref(i))(i = 2);
    
    ref cref var constant Ȥϰۤ뤳ȤդʤФʤʤ Ԥϡ˥ե󥯥ΤФԤϤǤϤʤ 㤨С
    int i; 
    var(i) = 1; // ok
    ref(i) = 1; // not ok, ref(i) is not a lambda functor
    
    Ȥʤ롣 ؿref cref ϤۤȤŪͳΤ¸ߤƤ롣 ơref var cref constant_ref֤뤳ȤǤ롣 ܤ Section 5.5 򸫤衣 ref cref Boost ŪŪΥ桼ƥƥؿǤΤǡboost ͡ॹڡľƤ롣

  • 󷿤ϥԡ뤳ȤϤǤǥեȤưǤϡconst ʻȤȤƳǼ롣

  • ĤμˤĤƤϡ򻲾ȤȤƳǼۤǼ 㤨С˼ i += _1ΰտޤ餫ˡ˥ե󥯥θƽФˤꡢŪʥԡǤϤʤѿiΤΤͤ˱ƶͿ뤳ȤǤ롣 ̤󤲤ȡȥ꡼α黻Ҥ const ǤʤȤȤƺǺΰȤ롣 Τʵ§ϼΤ褦ˤʤ롣

    • ʣ黻(+= *= ʤ)κ¦ΰϡconst ǤʤȤȤƳǼ롣

    • << ڤ >> κΰ줾졢 β줿 basic_ostream ڤ basic_istream Ƥˤϡΰ const ؤλȤȤƳǼ롣 ¾η˴ؤƤϡϥԡȤƳǼ롣

    • ݥ󥿤λѼˤƤϡconst Ǥʤ󷿤ϡconst ǤʤȤȤƳǼ롣 ϡݥ󥿤λѷ׻ˤäơconst Ǥʤ const ˤʤΤɤǤ롣



[1] ̩ˤϡC++ ɸ൬ʤǤϡfor_each ѹΤʤϢ³ Ǥꡢ for_eachϤؿ֥ȤϤΰѹ٤ǤʤƤ롣 ΰФ׵ɬפ˸롣 ʤʤ顢ƥ졼 mutable Ǥ¤ꡢfor_each ϰؤѤΤؿ֥奯ȤǤ뤫Ǥ롣 ȤϤstd::for_each εǽĤФƤŬڤ׵ Ĥ褦ʡ̤δؿƥץ졼Ȥ󶡤뤳ȤϴñǤ롣