제가 구독하는 블로그 중에
rein님의 C++0x를 써서 Closure 다시 만들기와 C++기반의 closure를 보고
제가 쓰고 있던 방법도 공개 합니다.


사용할 수 있는 곳은 여러 곳이 있겠습니다만..
다른 곳으로 Message를 Passing 한다던가 Timer를 쓴다던가 할 때
유용하게 쓸 수 있겠습니다.




typedef
function<void (void)> Closure;


C++0x가 지원되면 std.function을 써도 되고
그렇지 않으면 boost.function을 쓰면 됩니다.




void
freef(int a, int b)

{

    cout << a << " + " << b << " = " << a+b << endl;

}

 

struct Class

{

    Class(int a): a_(a) {}

 

    void memf(int b)

    {

        cout << a_ << " - " << b << " = " << a_-b << endl;

    }

 

    int a_;

};

 

vector<Closure> closures;

{

    int a = 10;

    closures.push_back(bind(freef, a, 4));

    closures.push_back(bind(&Class::memf, new Class(a), 2));

//  closures.push_back([=](){ cout << a << endl; });

}

 

foreach(Closure& closure, closures)

{

    closure();

}



마찬가지로 std.bind 나 boost.bind를 사용하고,
C++0x가 지원되면 lambda를 추가적으로 사용할 수 있습니다.




Posted by U∙Seung