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

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

改进如下:

#include 
#include 
#include 
#include 
using namespace std;
#include 
#include

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

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

    template 
    void RegisterType(string strKey){
        std::function function = Construct::invoke;
        RegisterType(strKey, function);
    }

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

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

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

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

private:
    template
    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 m_creatorMap;
};

你可能感兴趣的:(c/c++学习笔记7-代码实现IOC)