boost:any构建可变参数函数分发器

256 篇文章 3 订阅
149 篇文章 2 订阅
#include <iostream>
#include <string>
#include <algorithm>
#include <unordered_map>
#include <memory>
#include <functional>
#include <stdexcept>
#include <boost/noncopyable.hpp>
#include <boost/any.hpp>
class ioc_container : public boost::noncopyable {
public:
    ioc_container() = default;
    virtual ~ioc_container() = default;
public:
    template <typename T, typename depend, typename ...Args>
    void register_type(const std::string &key) {
        std::function<T *(Args...)>fun = [] (Args ...args) {
            return new T(new depend(args...));
        };
        register_type(key, fun);
    }
    template <typename T, typename ...Args>
    std::shared_ptr<T>resolve_shared(const std::string &key, Args ...args) {
        T *p = resolve<T>(key, args...);
        return std::shared_ptr<T>(p);
    }
private:
    void register_type(const std::string &key, boost::any value) {
        if (map_.find(key) != end(map_)) {
            throw std::invalid_argument("key has already existed.");
        }
        map_.emplace(key, value);
    }
    template <typename T, typename ...Args>
    T *resolve(const std::string &key, Args ...args) {
        auto it = map_.find(key);
        if (end(map_) == it) {
            return nullptr;
        }
        boost::any resolver = it->second;
        auto f = boost::any_cast<std::function<T *(Args...)>>(resolver);
        return f(args...);
    }
private:
    std::unordered_map<std::string, boost::any>map_;
};
struct base {
    virtual ~base() = default;
    virtual void fun() {
        std::cout << "I am base fun." << std::endl;
    }
};
struct derived0 : base {
public:
    derived0(int x, double y) : a(x), b(y) {
    }
    virtual void fun() override {
        std::cout << "I am derived0 fun = " << a + b << std::endl;
    }
private:
    int a;
    double b;
};
struct derived1 : base {
    virtual void fun() override {
        std::cout << "I am derived1 fun." << std::endl;
    }
};
struct Test {
    Test(base *p) : p_base(p) {
    }
    ~Test() {
        if (nullptr != p_base) {
            delete p_base;
            p_base = nullptr;
        }
    }
    void fun() {
        if (nullptr != p_base) {
            p_base->fun();
        }
    }
private:
    base *p_base = nullptr;
};
int main() {
    ioc_container ioc;
    ioc.register_type<Test, derived1>("derived1");
    auto c = ioc.resolve_shared<Test>("derived1");
    if (c != nullptr) {
        c->fun();
    }
    ioc.register_type<Test, derived0, int, double>("derived0");
    c = ioc.resolve_shared<Test>("derived0", 1, 1.0);
    if (c != nullptr) {
        c->fun();
    }

    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值