使用可变参数模板的工厂模式?

She*_*ohn 7 c++ factory-pattern variadic-templates c++11

我有一个抽象的课

template <class T> struct A { /* virtual methods */ };
Run Code Online (Sandbox Code Playgroud)

和几个具有各种构造函数的具体派生类

// The constructor of B takes 1 input
template <class T>
struct B
    : public A<T>
{
    B() { /* default ctor */ }
    B( T *input ) { /* initializer */ }

    // .. implement virtual methods
}


// The constructor of C takes 2 inputs
template <class T>
struct C
    : public A<T>
{
    double some_member;

    C() { /* default ctor */ }
    C( T *input, double& value ) { /* initializer */ }

    // .. implement virtual methods
}
Run Code Online (Sandbox Code Playgroud)

我创建了一个返回指针的工厂,A我试图使用可变参数模板将输入转发到所选派生类的构造函数.它工作正常,但我不得不复制带/不带构造函数输入的情况的代码,我正在寻找一种方法来防止代码重复(见下文).

template <class T>
struct A_Factory
{
    typedef std::shared_ptr<A> out_type;

    // Version without constructor inputs
    static out_type create( id_type id )
    {
        out_type out;
        switch (id)
        {
            // .. select the derived class
            case Type_B:
                out.reset( new B() );
                break;
        }
        return out;
    }

    // Version with constructor inputs
    template <class... Args>
    static out_type create( id_type id, Args&&... args )
    {
        out_type out;
        switch (id)
        {
            // .. select the derived class
            case Type_B:
                out.reset( new B( std::forward<Args>(args)... ) );
                break;
        }
        return out;
    }
};
Run Code Online (Sandbox Code Playgroud)

很抱歉这个问题很长.任何建议,使这个更短的赞赏.

Bar*_*rry 12

我们可以使用SFINAE和std::is_constructible类型特征(h/t Yakk)来解决这个问题.

我们只需要一个单独的create函数,它将调出到其他函数:

template <class... Args>
static std::shared_ptr<A> create( id_type id, Args&&... args )
{
    switch (id) {
    case Type_B:
        return create<B>(std::forward<Args>(args)...);
    case Type_C:
        return create<C>(std::forward<Args>(args)...);
    // ...
}
Run Code Online (Sandbox Code Playgroud)

每个基于标记的create函数将调用正确的构造函数或返回nullptr(如果这样的那个不存在):

// possible to construct
template <typename T, typename... Args>
std::enable_if_t<
    std::is_constructible<T, Args...>::value,
    std::shared_ptr<T>
>
create(Args&&... args) {
    return std::make_shared<T>(std::forward<Args>(args)...);
}

// impossible to construct
template <typename T, typename... Args>
std::enable_if_t<
    !std::is_constructible<T, Args...>::value,
    std::shared_ptr<T>
>
create(Args&&... ) {
    return nullptr;
}
Run Code Online (Sandbox Code Playgroud)

  • 事实上,我们真的不需要factory_tag吗?我们可以简单地使用`create <B>(std :: forward <Args>(args)...)` (2认同)