基于对象编程风格

函数适配器:将一种接口适配成另一种接口

#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
  • 例二
    Thread_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

你可能感兴趣的:(大并发服务器)