플밍

간단한 클래스멤버함수 콜백 본문

프로그래밍/C/C++

간단한 클래스멤버함수 콜백

너구리안주 2013. 10. 10. 20:35

C++에서 클래스멤버함수포인터를 직접 쓰는 대신 c++11에서 추가된 std::function 으로 간단하게 콜백을 구현할 수 있다.

(근데 이게 cygwin에서는 안먹히네요.  다 뜯어고쳤잖아잉~ ㅠㅠ)

굵은색을 주의깊게 살펴보자

#ads_1

#include <iostream>
#include <functional>


using namespace std;


class Child{
private:
    typedef std::function<void()> func1; //인수가 없는것
    typedef std::function<void(int, int)> func2; //인수가 있는것

    func1 onHandler1;
    func2 onHandler2;
public:

    void setHandler1(func1 f){
        onHandler1 = std::move(f);
    }

    void setHandler2(func2 f){
        onHandler2 = std::move(f);
    }

    void test(){
        onHandler1();
        onHandler2(30, 20);
    }
};

class Test{
public:
    void exec(){
        Child child;
        child.setHandler1(std::bind(&Test::callfunc1, this));
        child.setHandler2(std::bind(&Test::callfunc2, this, std::placeholders::_1, std::placeholders::_2)); //_1, _2는 인수
        child.test();
    }

    void callfunc1(){
        cout << "callfunc1" << endl;
    }

    void callfunc2(int n1, int n2){
        cout << "callfunc2: " << n1 << ", " << n2 << endl;
    }
};


int main(){

    Test t;
    t.exec();

    return 0;
   
}

<< 결과 >>

callfunc1
callfunc2: 30, 20

#ads_1

Comments