Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through variadic template parameters to create variable number of local variables?

I have many functions that are very similar but run with different number and type of local objects:

template <class T> T* create1( const std::vector<std::string>& names )
{
    A a( names[0] );
    B b( names[1] );
    C c( names[2] );

    if ( a.valid() && b.valid() && c.valid() )
        return new T( a, b, c );
    else
        return NULL;
}

template <class T> T* create2( const std::vector<std::string>& names )
{
    D d( names[0] );
    E e( names[1] );

    if ( d.valid() && e.valid() )
        return new T( d, e );
    else
        return NULL;
}

create1<ABC>( { "nameA", "nameB", "nameC" } );
create2<DE>( { "nameD", "nameE" } );

Would variadic template help me achieve a refactoring of those functions as this?

template <class T, typename Args...> T* create()
{
    // loop over Args and create 2 or 3 objects
    // if (....valid())
    //    return T( ... );
    // else
    //    return NULL;
}

create<ABC,A,B,C>( { "nameA", "nameB", "nameC" } );
create<DE,D,E>( { "nameD", "nameE" } );

Checked How can I iterate over a packed variadic template argument list? and iterating over variadic template's type parameters with no success. Can't see how I could create a variable number of local objects of different kind...

like image 943
jpo38 Avatar asked Nov 18 '16 14:11

jpo38


1 Answers

First, don't take your names as a vector. Take them as a parameter pack. And, moreover, take them as a pack of what you actually want:

bool is_valid() { return true; }
template <class T, class... Ts>
bool is_valid(T& arg, Ts&... args) {
    return arg.valid() && is_valid(args...);
}

template <class T, class... Args>
T* create(Args&&... args) {
    if (is_valid(args...)) {
        return new T{args...};
    }
    else {
        return nullptr;
    }
}

And now just pass the right thing in:

create<T>(A{"nameA"}, B{"nameB"}, C{"nameC"});
create<T>(D{"nameD"}, E{"nameE"});

If, for some reason, you really want to separate the types and the names, you can do that too:

template <class T, class... Cs, class... As>
T* create_classes(As&&... args) {
    return create<T>(Cs{std::forward<As>(args)}...);
}
like image 63
Barry Avatar answered Nov 22 '22 03:11

Barry