I have never used variadic templates myself, but think I could need them now. Suppose I have a class
class A {
int Kern;
template<int> void func_a(int, double) const;
template<int> void func_b(double, double, char) const;
template<int> unsigned func_c(float, std::vector<int> const&) const;
public
/* ... */
void FuncA(int, double) const;
void FuncB(double, double, char) const;
unsigned FuncC(float, std::vector<int> const&) const;
};
where the definitions of A::FuncA()
etc. are all of the form
void A::FuncA(int i, double x) const
{
switch(Kern) {
case 1: return func_a<1>(i,x);
case 2: return func_a<2>(i,x);
case 3: return func_a<3>(i,x);
/* ... */
}
}
I currently implement this switch with a C-macro
#define SwitchKernMacro(KERN,FUNC) \
switch(KERN) { \
case 1: FUNC(1); \
case 2: FUNC(2); \
case 3: FUNC(3); \
/* ... */ \
}
such that
void A::FuncA(int i, double x) const
{
#define FuncK(KERN) return func_a<KERN>(i,x);
SwitchKernMacro(Kern,FuncK);
#undef FuncK
}
I like to avoid this C-macro in favour of a variadic template solution, such that the implementation of my functions becomes simply (or similar)
void A::FuncA(int i, double x) const
{ return SwitchKern(Kern,func_a,i,x); }
void A::FuncB(double a, double b, char c) const
{ return SwitchKern(Kern,func_b,a,b,c); }
unsigned A::FuncC(float f, std::vector<int> const&v) const
{ return SwitchKern(Kern,func_c,f,v); }
How should the template SwitchKern
look like?
EDIT
there seems to be some confusion about C++ templates and when they can be used. Suppose, I only have the following very simple functions
class A {
int Kern;
template int> void simple() const;
public:
void Simple() const
{
switch(K) {
case 1: return simple<1>();
case 2: return simple<2>();
case 3: return simple<3>();
default: return simple<0>();
}
}
/* ... */
};
then I can also implement A::Simple()
via
class A {
/* ... */
template<int> friend struct simple_aux;
};
template<class T, template<int> class SimpleAux>
void Switch(int K, const T* a) {
switch(K) {
case 1: return SimpleAux<1>(a)();
case 2: return SimpleAux<2>(a)();
case 3: return SimpleAux<3>(a)();
default: return SimpleAux<0>(a)();
}
}
template<int k> struct simple_aux
{
const A*const a;
explicit simple_aux(const A*a__) : a(a__) {}
void operator()() { return a->simple<k>(); }
};
void A::Simple() const
{ Switch<A,simple_aux>(K,this); }
However, this solution does not allow for return type different than void
and for arbitrary arguments to the functions A::Simple()
(passed to A::simple<>()
). My question was how to add these functionalities using variadic templates