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