c ++中具有可变参数的函数映射

时间:2017-02-04 18:44:36

标签: c++ c++11 factory-pattern

来自

  

Martin Reddy的C ++ API设计 - 第3章(第3.3.3节)   可扩展工厂示例)

我发现Factory模式的这种实现非常有效,它允许用户在运行时注册回调函数(本质上是派生类的构造函数),最终可以在创建该类型的对象时调用。代码如下所示,取自教科书 -

文件:rendererfactory.h

class RendererFactory
{
public:
    typedef IRenderer *(*CreateCallback)();
    static void RegisterRenderer(const std::string &type, CreateCallback cb);
    static void UnregisterRenderer(const std::string &type);
    static IRenderer *CreateRenderer(const std::string &type);
private:
    typedef std::map<std::string, CreateCallback> CallbackMap;
    static CallbackMap mRenderers;
};

文件:rendererfactory.cpp

#include "rendererfactory.h"

// instantiate the static variable in RendererFactory
RendererFactory::CallbackMap RendererFactory::mRenderers;

void RendererFactory::RegisterRenderer(const std::string &type, CreateCallback cb)
{
    mRenderers[type] = cb;
}

void RendererFactory::UnregisterRenderer(const std::string &type)
{
    mRenderers.erase(type);
}

IRenderer *RendererFactory::CreateRenderer(const std::string &type)
{
    CallbackMap::iterator it = mRenderers.find(type);
    if (it != mRenderers.end())
    {
        // call the creation callback to construct this derived type
        return (it->second)();
    }
    return NULL;
}

class UserRenderer : public IRenderer
{
public:
    ~UserRenderer() {}
    static IRenderer *Create() { return new UserRenderer(); }
};

文件:main.cpp

int main(int, char **)
{
    // register a new renderer
    RendererFactory::RegisterRenderer("user", UserRenderer::Create);

    // create an instance of our new renderer
    IRenderer *r = RendererFactory::CreateRenderer("user");

    r->Render();

    delete r;

    return 0;
}

我对此代码的限制是它假定是派生对象的构造函数,不带任何参数。例如,如果我有一个派生类 -

class UserRendererMultiArgs : public IRenderer
{
public:
    UserRendererMultiArgs(int, int);
    ~UserRendererMultiArgs() {}
    static IRenderer *Create() { 
        return new UserRendererMultiArgs(); //Incorrect : need to call UserRendererMultiArgs(int, int) ??? 
    }
};

如何在RendererFactory类维护的地图中实现使用变量参数注册回调的相同结果?

我有使用varargs但我不知道该怎么做?!

2 个答案:

答案 0 :(得分:1)

忽略工厂模式并使用问题的标题,然后这可能会做你想要的:

#include <map>
#include <memory>
#include <string>

struct IRenderer {};

class UserRendererMultiArgs : public IRenderer {
    public:
    UserRendererMultiArgs(int, int) {}
    ~UserRendererMultiArgs() {}
    static IRenderer *Create(int i1, int i2) {
        return new UserRendererMultiArgs(i1, i2);
    }
};

template <class... Args>
struct MapHolder{
    static std::map<std::string, IRenderer *(*)(Args...)> CallbackMap;
};

template <class... Args>
std::map<std::string, IRenderer *(*)(Args...)> MapHolder<Args...>::CallbackMap;

class RendererFactory {
    public:
    template <class... Args>
    static void RegisterRenderer(std::string name, IRenderer *(*Callback)(Args...)) {
        MapHolder<Args...>::CallbackMap[name] = Callback;
    }

    template <class... Args>
    static IRenderer *Create(const std::string &name, Args &&... args) {
        return MapHolder<Args...>::CallbackMap[name](std::forward<Args>(args)...);
    }
};

int main() {
    RendererFactory::RegisterRenderer("user", &UserRendererMultiArgs::Create);
    std::unique_ptr<IRenderer> r{RendererFactory::Create("user", 42, 3)};
}

demo to play with

在C ++ 14中,您有可变模板,不需要MapHolder,但标签指定了C ++ 11。

答案 1 :(得分:0)

如果您在编译时知道参数,则可以使用

RendererFactory::RegisterRenderer("multiuser", []{
    return new UserRendererMultiArgs(1, 2);
});

如果您在编译时不知道参数,可以使用

int i = 0, j = 0;
std::cin >> i >> j;
RendererFactory::RegisterRenderer("multiuser", [i, j]{
    return new UserRendererMultiArgs(i, j);
});

但是,现在lambda携带状态,它不再被分配给函数指针,因此您需要将CreateCallback的类型更改为std::function<IRenderer *()>,这会因动态内存分配而产生一些成本需要捕获任意大小的函数对象。