Is there a way to handle a variable number of parameters in a template class?
-
03-07-2019 - |
Question
I have a set of callback classes that I use for handling callbacks with variable numbers of parameters. Right now I have about 6 different instances of it to handle differing numbers of arguments. Is there a way to make one instance than can handle a variable number of arguments?? Ultimately I would love to have each parameter be a POD type or a class pointer, or a struct pointer. Any ideas?
template <class T>
class kGUICallBackPtr
{
public:
kGUICallBackPtr() {m_obj=0;m_func=0;}
void Set(void *o,void (*f)(void *,T *));
inline void Call(T *i) {if(m_func) m_func(m_obj,i);}
inline bool IsValid(void) {return (m_func!=0);}
private:
void *m_obj;
void (*m_func)(void *,T *);
};
template <class T,class U>
class kGUICallBackPtrPtr
{
public:
kGUICallBackPtrPtr() {m_obj=0;m_func=0;}
void Set(void *o,void (*f)(void *,T *,U *));
inline void Call(T *i, U *j) {if(m_func) m_func(m_obj,i,j);}
inline bool IsValid(void) {return (m_func!=0);}
private:
void *m_obj;
void (*m_func)(void *,T *,U *j);
};
Solution
Not yet in the language itself but C++0x will have support for variadic templates.
OTHER TIPS
C++0x variatdic templates is your best bet, but it will also be a while before you can use them.
If you need sequences of types today, take a look at MPL's vector of types, as well as other type sequence types. It's part of the Boost library. It allows you to provide a template argument that is a sequence of types, instead of just a single type.
How about sidestepping this issue through the use of Boost Bind? You could make your code accept a single argument, or none at all, and bind arguments you need at the call site.
My first choice would be to use boost::bind, boost::function, or std::bind/std::function and/or c++11 lambda's to achieve your goal. But if you need to roll your own functor then I would use boost fusion to create a 'fused functor' that takes a single template argument.
Ultimately all of these libraries use pre-processor macros to enumerate all possible options to work around lack of varidic templates.