3. Introduction

3.1. Motivation

ߤǤ C++ ɸ饤֥[C++98]ΰȤʤäƤɸƥץ졼ȥ饤֥ (STL)[STL94] ѤΥƥʤȥ르ꥺΥ饤֥Ǥ롣Ūˤ STL 르ꥺϥƥʤǤؿ֥𤷤롣δؿ֥Ȥϥ르ꥺ˰ȤϤ롣

ؿƤӽФʸˡ˽äƸƽФ뤤ʤ C++ ι¤ؿ֥ȤǤ롣 STL ˤϤĤΰŪӤΤˡؿ֥Ȥ餫Ƥ롣(pluslessnot1ʤɤ) 㤨Сplus ɸŪʼΰĤϼΤ褦ˤʤ롣

template <class T> : public binary_function<T, T, T>
struct plus {
  T operator()(const T& i, const T& j) const {
    return i + j; 
  }
};
쥯饹 binary_function<T, T, T> ˤϡؿ֥Ȥΰ֤ͤηΤ typedef ¸ߤ롣 typedef ϴؿ֥ȤŬǽˤ뤿ɬפǤ롣

˵󤲤褦ʴŪʴؿ֥Ȥ˲äơŬǽؿΰΰĤñؿ뤿 Х ƥץ졼Ȥ¸ߤ롣 㤨СΤ褦ʴؿ֥ȤŪ˵ҤʤȤ plusƥץ졼ȤȥХƥץ졼Ȥΰbind1stѤʵǽ¸Ǥ롣

class plus_1 {
  int _i;
public:
  plus_1(const int& i) : _i(i) {}
  int operator()(const int& j) { return _i + j; }
};
ʲĤμƱδؿ֥Ȥ롣 ĤޤꡢƽФ줿ȤȤؿ֥Ȥΰ1ä̤֤
plus_1(1)
bind1st(plus<int>(), 1)
μʬ plus<int>() Ĥιפ׻ؿ֥ȤǤ롣ơbind1st ʬŪ 1 «ơδؿ֥ȤƽФ 嵭δؿ֥Ȥλʲ󼨤롣ʲΥɤϤ륳ƥ a Ǥ 1 äơη̤ɸϥȥ꡼ cout ؽϤ롣
transform(a.begin(), a.end(), ostream_iterator<int>(cout),
          bind1st(plus<int>(), 1));

binder ƥץ졼ȤŪŬѤǤ褦ˤ뤿ˡSTL ϴؿؤΥݥ󥿤仲ȡдؿؤΥݥ󥿤Ŭǽˤ ץ 󶡤Ƥ롣 ˡɸλͤĥؿιޤ STL μ⤢ [SGI02]

餹٤ƤμʤɸϰĤǤ롣 STL 르ꥺθƽФ̵̾ؿǤ褦ˤ뤳ȤǤ롣 ȡɤΰؿؤΰȤϤȤǤ롣 ɸʬŪˤ¸Ǥʤ ñ򸫤Ƥʬ̤ꡢɸμʤѤ̵̾ؿϰˤ ե󥯥䡢ץХؿޤʣʼ򤷤ˤʤäƤޤ ˲äɸμʤŬѤΤ˽פ¤롣 ɸΥХǤϡؿΰΤΰĤ«뤳ȤǤʤ 3 4 Ȥä 3 İʾȤؿΤΥХ¸ߤʤΤǤ롣

Boost Lambda Library Ͼ嵭Τ褦褹롣

  • ľŪʸˡˤäƴñ̵̾ؿǤ롣 嵭ϼΤ褦˵ҤǤ롣

    transform(a.begin(), a.end(), ostream_iterator<int>(cout), 
              1 + _1);
    
    ޤϡľŪ
    for_each(a.begin(), a.end(), cout << (1 + _1));
    

  • «˴ؤۤȤɤ¤ϤʤʤꡢºŪˤ C++ ΤʤؿǤǤդΰ«뤳ȤǤ롣

  • ؿϰŪ˥ݡȤƤΤǸġδؿפǤ롣

3.2. Introduction to lambda expressions

˼ϴؿˤƤϰŪʤΤǤ롣 ʸˡϸˤä͡Ǥ롣(˷׻ηˤäƤۤʤ) ˼δŪʷϼΤ褦Ǥ롣

lambda x1 ... xn.e
˼̵̾ؿΤ褦˹롣
  • δؿβ : x1 ... xn

  • x1 ... xn ؿͤ׻뼰 e

˼δñ󤲤ȡ
lambda x y.x+y
˴ؿŬѤȤϡŪʰºݤΰ֤뤳ȤǤ롣
(lambda x y.x+y) 2 3 = 2 + 3 = 5 

C++ ˤ˼Ǥϡlambda x1 ... xn Ȥʬʤ Ūʰͽ줿̾äƤ롣 ߤΥ饤֥ΥСǤϡ ץ졼ۥȸƤФ뤳Τ褦ͽ줿ŪʰĤ롣 _1 _2 _3. Ǥ롣 줾˼Ǵؿ줿ؿ졢軰򼨤 㤨С

lambda x y.x+y
C++ ˤ
_1 + _2
Ȥʤ롣

äơC++Φ˼ˤʸˡŪʥɤ¸ߤʤ ڥɤȤƥץ졼ۥλȤ뤳Ȥϡα黻ҤθƽФϦ˼Ǥ뤳Ȥ̣롣 ϱ黻ҤθƽФ˴ؤƤΤ ؿƽФ䡢¤㥹Ȥʤɤޤޤ줿˼ϡ̤ʸˡŪ¤ɬפȤʤ롣 ˽פʤȤˤϡؿƽФǤϡؿ boost::lambda::bind ǥåפɬפ롣 㤨С

lambda x y.foo(x,y)
Ȥ˼ͤƤߤ롣 μб C++ μϡ foo(_1, _2) ǤϤʤ
bind(foo, _1, _2)
Ȥʤ롣 μΦ˼bind ȸƤ֤Ȥˤ롣

˼ C++ δؿ֥Ȥ롣äơؿŬѤʸˡ¾δؿ֥ȤθƽФƱͤǤ롣 ʤ(_1 + _2)(i, j) 褦ʷǤ롣

3.2.1. Partial function application

ؿ boost::lambda::bind ϼ¼ʬؿŬǤ롣 ʬؿŬѤǤϡؿΰΤĤ«롣 ŬѤη̤̤ʴؿǤ롣ơδؿΰϤ餯δؿ⾯ʤ «ƤʤȤʤäƸƽФ줿Ȥ οؿ«줿ȤǤʤȤޤȤ᤿ꥹȤäƸδؿƽФ

3.2.2. Terminology

˼ϴؿ롣C++ Φ˼ɾȤˡ˴ؿ֥(ե󥯥)ۤ롣Τ褦ʴؿ֥ȤؤΤˡ˥ե󥯥 ȤդѤ롣 äơθˡ˽С˼ɾ̤Ϧ˥ե󥯥Ǥ롣