views:

115

answers:

2

I need to repeatedly make calls to a template function with different classes defined elsewhere in the code, like so:

MyTemplateFunction<ClassOne>( &AnotherTemplateFunction<ClassOne> );
MyTemplateFunction<ClassTwo>( &AnotherTemplateFunction<ClassTwo> );
MyTemplateFunction<ClassThree>( &AnotherTemplateFunction<ClassThree> );
MyTemplateFunction<ClassFour>( &AnotherTemplateFunction<ClassFour> );

Is there a way to create an array of the specializations for the classes ClassOne, ClassTwo etc. so I can simply iterate over the array for better maintainability.

edit: I am specifically using the register_exception_translator function in Boost.Python. So I don't really have a choice. Its a third party function I have to call for all of my classes, which are over 50 in number in my project. Repeating the calls like this has been a messy experience when adding or modifying classes.

+4  A: 

You should look into Boost.MPL, specifically sequences.

Space_C0wb0y
+1 This in my opinion is a good option if Boost.MPL was used to solve more than a simple refactoring issue. For my case I didn't want to add another dependency for a very small problem.
sarshad
+2  A: 

Something like this should suffice

template<typename I, typename N> struct cons { };
struct nil { };

template<typename T, typename U>
void call(cons<T, U>) {
  MyTemplateFunction<T>(&AnotherTemplateFunction<T>);
  call(U());
}

void call(nil) { }

typedef cons<ClassA, cons<ClassB, cons<ClassC, nil> > > conses;
int main() {
  call(conses());
}
Johannes Schaub - litb
+1: For particular applications, the manual work is often easier than MPL.
Potatoswatter
This is a nice solution without any additional dependency. And I learned some new things. Thanks.
sarshad