jpo38 jpo38 - 1 year ago 263
C++ Question

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

Answer Source

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)}...);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download