1 使用C++11实现委托机制

1.1 TinyDelegate

1.1.1 代码

TinyDelegate.hpp

#ifndef TINY_DELEGATE_H
#define TINY_DELEGATE_H

#include <functional>
#include <chrono>
#include <string>
#include <list>
#include<algorithm>


template<typename ... arguments>
class TinyDelegate
{
public:
    TinyDelegate() = default;
    virtual~TinyDelegate() = default;

public: 
    template<typename callable>
    TinyDelegate& operator += (const callable& func)
    {
        m_Funtion_List.push_back(std::function<void(arguments...)>(func));
        return *this;
    }

    template<typename Class, typename Method>
    TinyDelegate& operator += (const std::function<void(arguments...)>& func)
    {
        m_Funtion_List.push_back(func);
        return *this;
    }

    //TinyDelegate& operator -= (const std::function<void(arguments...)>& func)
    //{
    //  void(*const* ptr)(arguments...) = func.target<void(*)(arguments...)>();

    //  for (auto iter = m_Funtion_List.begin();iter != m_Funtion_List.end();iter++)
    //  {
    //      if (ptr)
    //      {
    //          if (*ptr == *iter)
    //          {
    //              m_Funtion_List.erase(iter);
    //              break;
    //          }
    //      }
    //  }
    //}

    void operator()(arguments... params)
    {
        for (auto func : m_Funtion_List)
        {
            func(params...);
        }
    }


private:
    std::list<std::function<void(arguments...)>> m_Funtion_List;
};

#endif

1.1.2 测试代码

#include <iostream>
#include <thread>
#include "TinyDelegate.hpp"

void print()
{
    std::cout << "print" << std::endl;
}

void print_string(const std::string& str)
{
    std::cout << "print_string : " << str << std::endl;
}

void add()
{
    std::cout << "add" << std::endl;
}

class Test
{
public:
    Test() = default;
    virtual~Test() = default;

public:
    void add()
    {
        std::cout << "Test::add" << std::endl;
    }
};


int main()
{
    Test test;
    TinyDelegate<> t_Delegate;

    t_Delegate += print;
    t_Delegate += add;
    t_Delegate += std::bind(&Test::add, test);
    t_Delegate += []() { std::cout << "lambda" << std::endl; };

    t_Delegate();


    TinyDelegate<std::string> t_Delegate_string;

    t_Delegate_string += print_string;

    t_Delegate_string("hello");

    getchar();

    return 0;
}

运行结果:

C++11 – 委托机制的实现TinyDelegate-StubbornHuang Blog

1.1.3 缺陷

由于std::function无法进行比较,暂时未实现-=操作符的重载,暂时未提供通过-=操作符删除委托的功能。也就是目前版本只能增加委托函数,不能删除委托函数。