대상 기반 프로그래밍 스타일

함수 어댑터: 한 인터페이스를 다른 인터페이스로 어댑터
#include
#include
using namespace std;

class Foo{
public:
    void memberFunc(double d, int i, int j)
    {
        cout << d << endl;
        cout << i << endl;
        cout << j << endl;
    }
};

int main()
{
    Foo foo;
    using placeholders::_1;
    function<void (int)> fp = bind(&Foo::memberFunc, &foo, 0.5, _1, 10);
    fp(100);
    return 0;
}

컴파일링:
g++ -g -std=c++11 bf_test.cpp -o bf_test
  • 예2Thread_test.cpp:
  • #include"Thread.h"
    #include
    #include
    using namespace std;
    
    
    void threadFunc()
    {
        cout << "ThreadFunc..." << endl;
    }
    
    void threadFunc2(int count)
    {
        while(count--){
            cout << "threadFunc2()..." << endl;
            sleep(1);
        }
    }
    
    int main()
    {
        Thread t1(threadFunc);
        Thread t2(bind(threadFunc2, 3));
        t1.Start();
        t2.Start();
        t1.Join();
        t2.Join();
        return 0;
    }
    Thread.h :
    #include"Thread.h"
    #include
    #include
    using namespace std;
    
    
    void threadFunc()
    {
        cout << "ThreadFunc..." << endl;
    }
    
    void threadFunc2(int count)
    {
        while(count--){
            cout << "threadFunc2()..." << endl;
            sleep(1);
        }
    }
    
    int main()
    {
        Thread t1(threadFunc);
        Thread t2(bind(threadFunc2, 3));
        t1.Start();
        t2.Start();
        t1.Join();
        t2.Join();
        return 0;
    }
    Thread.cpp :
    #include "Thread.h"
    #include<iostream>
    using namespace std;
    
    Thread::Thread(const ThreadFunc& func):func_(func)
    {
        cout << "create Thread..." << endl;
    }
    
    
    void Thread::Start()
    {
        pthread_create(&threadId_t, NULL, ThreadRoutine, this);
    }
    
    
    void* Thread::ThreadRoutine(void* arg)
    {
        // ( this )    
        Thread* thread = static_cast<Thread*>(arg);
        thread->Run();
        return NULL;
    }
    
    void Thread::Join()
    {
        pthread_join(threadId_t, NULL);
    }
    
    // 
    void Thread::Run()
    {
        func_();
    }
    Thread.h :
    #ifndef _THREAD_H_
    #define _THREAD_H_
    
    #include
    #include
    class Thread{
    public:
        typedef std::function<void()> ThreadFunc;
        explicit Thread(const ThreadFunc& func);
    
    
        void Start();
        void Join();
    
    private:
        static void* ThreadRoutine(void* arg);
    
        void Run();
        ThreadFunc func_;
        pthread_t threadId_t;
    
    };
    
    #endif

    좋은 웹페이지 즐겨찾기