Re: Small meta-programming exercise
mathieu wrote:
I was faced with the following issue: trying to avoid code
duplication in complexfunc1 / complexfunc2:
struct S
{
template <typename T1, typename T2>
void Foo() const { }
template <typename T1, typename T2>
void Bla(int i) const { }
};
void complexfunc1()
{
S s;
s.Foo<int,float>();
s.Foo<double,float>();
s.Foo<long,float>();
}
void complexfunc2(int i)
{
S s;
s.Bla<int,float>(i);
s.Bla<double,float>(i);
s.Bla<long,float>(i);
}
And how are those functions used? Are they really *that* "complex" or
are they more complex than you show here?
At first it looked easy but after much struggle all I could come up
with is the following solution:
A solution to merge the two functions? A solution to make one out of
two similar? Are they really already *that* similar?
template <int T> struct SHelper;
template <> struct SHelper<0>
{
template <typename T1, typename T2>
static void FooBla(S const & s, int ) { s.Foo<T1,T2>(); }
};
template <> struct SHelper<1>
{
template <typename T1, typename T2>
static void FooBla(S const & s, int i) { s.Bla<T1,T2>(i); }
};
template <int TT>
void complexfunc(int i)
{
S s;
SHelper<TT>::template FooBla<int,float>(s,i);
SHelper<TT>::template FooBla<double,float>(s,i);
SHelper<TT>::template FooBla<long,float>(s,i);
}
Am I missing something obvious or passing member function as template
parameter is not that easy.
Uh... And how is your 'complexfunc' used? You have avoided code
duplication in some sense, but the function is really hard to read now
and the use of it is also somewhat ugly (I suspect). What exactly was
the point? Two functions, each with four statements aren't that
expensive, are they? What's wrong with keeping them both after renaming
them to be overloaded instead of remembering '1' and '2'?
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask