Dom Jackson a écrit :
Hello -
I have a problem where I need to test some numeric code using a
variety of built-in integer types:
obj_type1 = obj_type2 OP obj_type3; // is obj_type1 correct?
If I test with 10 built-in integer types, then I get 1000 permutations
of the above statement. If I then test a dozen different operators, I
get over 10,000 test operations.
Obviously, I need some generic way to handle this. I can't immediately
see a static/template-based solution, but it seems like I should be
able to do this dynamically. [snip]
Perhaps a typelist is what you need. Giving an example with addition:
//generic typelist system
template <typename T1, typename T2>
struct TypeList
{
typedef T1 Head;
typedef T2 Tail;
};
//end of list type
struct NullType {};
// define a list with your types
typedef TypeList<long, TypeList<int, TypeList<short, NullType IntList;
//implementation of the plus operation as recursive template
template < typename TList1 , typename TList2 , typename TListInistruct
plus_operation_imp;
//general case of recursion
template < typename T1, typename T2 , typename T3, typename T4 ,
typename TListIni>
struct plus_operation_imp< TypeList<T1, T2, TypeList<T3, T4,
TListIni :
public plus_operation_imp< TypeList<T1, T2, T4, TListIni>
{
T1 operator()(T1 lhs,T3 rhs)
{
return lhs+rhs;
}
};
//recursion at end of list for right hand side
template < typename T1, typename T2 , typename T3 , typename TListIni>
struct plus_operation_imp< TypeList<T1, T2, TypeList<T3, NullType>
,TListIni:
public plus_operation_imp< T2 , TListIni, TListIni>
{
T1 operator()(T1 lhs,T3 rhs)
{
return lhs+rhs;
}
};
//recursion at end of both list
template < typename T1, typename T3 , typename TListIni>
struct plus_operation_imp< TypeList<T1, NullType, TypeList<T3,
NullType, TListIni>
{
T1 operator()(T1 lhs,T3 rhs)
{
return lhs+rhs;
}
};
//type to initialize recursion
template<typename TList>
struct plus_operation: public plus_operation_imp<TList,TList,TList>
{};
//here is your functor
plus_operation<IntListmyoperation;
Then you can call myoperation with any combinaison of parameters.
myoperation(long,long);
myoperation(long,int);
myoperation(int,int);
myoperation(int,long);
....
You might even automatize that with MPL but I am not familiar enough
with it to tell you.
Michael