Factory pattern using variadic template?
Asked Answered
C

1

8

I have an abstract class

template <class T> struct A { /* virtual methods */ };

and several concrete derived classes with various constructors

// 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
}

I created a Factory that returns pointers to A, and I am trying to use variadic templates to forward inputs to the constructor of the selected derived class. It is working fine, but I had to duplicate the code for the cases with/without constructor inputs, and I am looking for a way to prevent code duplication (see below).

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;
    }
};

Very sorry for the long question. Any suggestion to make this shorter appreciated.

Cahoon answered 31/1, 2015 at 21:8 Comment(12)
A pack expansion can be empty so the separate overload isn't needed. You're better off with just the second.Indefectible
Interesting, well you're probably right but my compiler doesn't seem to agree :?Cahoon
@0x499602D2 Ctrl+C New Answer Ctrl+V.Meridethmeridian
The zero argument create function should be deleted, as it is useless. You still have a problem because code that constructs B with 1 2 and 3 arguments will be generated, and only 2 arguments is valid.Sclerotomy
@Sh3ljohn you should append the compiler errors in that case to your question.Meridethmeridian
Unless you can pass in id_type as a template argument, your only option is making all the constructors take the same arguments.Purine
@Purine while you have identified the problem, you presumed there was no solution to it. This is C++, that problem can be solved (so long as run-time failure is an option).Sclerotomy
@Meridethmeridian the errors that happen when Sh3ljohn tries to solve the problem themselves (ie, only uses one create function).Sclerotomy
@Yakk I'm curious to see how you solve it then.Purine
@Purine Write T* maybe_new<T, Args...> that returns nullptr if you cannot construct a T from Args.... Uses tag dispatching to dispatch to two implementations, one return nullptr; and the other return new T(std::forward<Args>(args)...);Sclerotomy
@Yakk Ahhhhh. Nice. You want to write that as an answer or should I?Purine
@barry I still don't know what the OP's problem is: I have a guess. But the OP has failed to post what they tried, and what error messages they got when they tried, so ...Sclerotomy
P
15

We can solve this using SFINAE and the std::is_constructible type trait (h/t Yakk).

We just need one single create function, that will dispatch out to other functions:

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)...);
    // ...
}

Each tag-based create function will either call the correct constructor OR return nullptr if such a one does not exist:

// 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;
}
Purine answered 31/1, 2015 at 21:37 Comment(4)
In fact, we don't really need factory_tag right? we can simply use create<B>(std::forward<Args>(args)...)Karelian
@EricZheng Indeed we don't.Purine
What is the advantage of using variadic templates in this pattern?,Hoover
@Hoover B and C have multiple constructors, this can call any of themTrump

© 2022 - 2024 — McMap. All rights reserved.