Re: simplifying multiple template creation/dispatch
Paul Miller <paul@fxtech.com> wrote in
news:Y9zPn.260573$XD2.14888@news.usenetserver.com:
I have a ton of code like this:
template <class T>
static void DoSomething_T(int arg1, int arg2, int arg3)
{
...
}
...
if (type == 1)
DoSomething_T<Type1>(arg1, arg2, arg3);
else if (type == 2)
DoSomething_T<Type2>(arg1, arg2, arg3);
else if (type == 3)
DoSomething_T<Type3>(arg1, arg2, arg3);
I'd like to simplify the dispatch part at the end, to something like
this:
DoSomethingBasedOnType(type, DoSomething_T, arg1, arg2, arg3);
Where DoSomethingBasedOnType() is ALWAYS the same set of ifs, where it
then calls the DoSomething_T<Type1> or DoSomething_T<Type2> or
DoSomething_T<Type3> passing along whatever arguments are passed after
the template name. The number/types of arguments can be different with
each "call" of DoSomethingBasedOnType().
Can this be achieved with a macro or some kind of template/functor
arrangement?
An example to give an idea: (Vector::Byte etc are enum values here
corresponding to types).
#define DISPATCH_INTEGRAL(ELEMTYPE,FUNCTION,ARGS) \
switch(ELEMTYPE) {\
case Vector::Byte: FUNCTION<unsigned char>ARGS; break;\
case Vector::UnsignedShort: FUNCTION<unsigned short>ARGS; break;\
case Vector::UnsignedInt: FUNCTION<unsigned int>ARGS; break;\
case Vector::UnsignedInt64: FUNCTION<uint64_t>ARGS; break;\
case Vector::Char: FUNCTION<char>ARGS; break;\
case Vector::Short: FUNCTION<short>ARGS; break;\
case Vector::Int: FUNCTION<int>ARGS; break;\
case Vector::Int64: FUNCTION<int64_t>ARGS; break;\
default: throw Nbaseutil::Exception(Nbaseutil::ERR_NOTIMPLEMENTED,
Nbaseutil::Printf("Function " #FUNCTION " not implemented for data type
'%s'")(Vector::TypeToString(ELEMTYPE)));\
};
Usage examples:
DISPATCH_INTEGRAL(ElemType(), serialize1_tmpl, (Pointer(), n, buffer));
DISPATCH_INTEGRAL(t, return std::numeric_limits, ::max());
Generalization to multiple template parameters left as an exercise for
the reader ;)
hth
Paavo