c/c++学习笔记7-代码实现IOC

2018-01-19  本文已影响0人  scott_yu779

原文:c++代码框架实现ioc

改进如下:

#include <string>
#include <map>
#include <memory>
#include <functional>
using namespace std;
#include <Any>
#include<NonCopyable>

class IocContainer : NonCopyable
{
public:
    IocContainer(void){}
    ~IocContainer(void){}

    template <class T>
    void RegisterType(string strKey){
        typedef T* I;
        std::function<I()> function = Construct<I, T>::invoke;
        RegisterType(strKey, function);
    }

    template <class I, class T, typename... Ts>
    void RegisterType(string strKey){
        std::function<I* (Ts...)> function = Construct<I*, T, Ts...>::invoke;
        RegisterType(strKey, function);
    }

    template <class I>
    I* Resolve(string strKey){
        if (m_creatorMap.find(strKey) == m_creatorMap.end())
            return nullptr;
        Any resolver = m_creatorMap[strKey];
        std::function<I* ()> function = resolver.AnyCast<std::function<I* ()>>();
        return function();
    }

    template <class I>
    std::shared_ptr<I> ResolveShared(string strKey){
        auto b = Resolve<I>(strKey);
        return std::shared_ptr<I>(b);
    }

    template <class I, typename... Ts>
    I* Resolve(string strKey, Ts... Args){
        if (m_creatorMap.find(strKey) == m_creatorMap.end())
            return nullptr;
        Any resolver = m_creatorMap[strKey];
        std::function<I* (Ts...)> function = resolver.AnyCast<std::function<I* (Ts...)>>();
        return function(Args...);
    }

    template <class I, typename... Ts>
    std::shared_ptr<I> ResolveShared(string strKey, Ts... Args){
        auto b = Resolve<I, Ts...>(strKey, Args...);
        return std::shared_ptr<I>(b);
    }

private:
    template<typename I, typename T, typename... Ts>
    struct Construct{
        static I invoke(Ts... Args) { return I(new T(Args...)); }
    };
    void RegisterType(string strKey, Any constructor){
        if (m_creatorMap.find(strKey) != m_creatorMap.end())
            throw std::logic_exception("this key has already exist!");
        m_creatorMap.insert(make_pair(strKey, constructor));
    }

private:
    unordered_map<string, Any> m_creatorMap;
};
上一篇 下一篇

猜你喜欢

热点阅读