Re: Small meta-programming exercise
mathieu wrote:
Hi there,
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);
}
At first it looked easy but after much struggle all I could come up
with is the following solution:
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.
A slightly different solution (run-time decision instead of specialization):
class Caller
{
bool m_bvoid;
int m_i;
public:
Caller() : m_bvoid(true) {}
Caller(int i) : m_bvoid(false), m_i(i) {}
template<class T1, class T2>
void call_it(S const & s) const
{
if (m_bvoid)
s.Foo<T1,T2>();
else
s.Bla<T1,T2>(m_i);
}
};
void complexfunc(Caller const& c = Caller())
{
S s;
c.call_it<int,float>(s);
c.call_it<double,float>(s);
c.call_it<long,float>(s);
}
int main()
{
complexfunc();
complexfunc(42);
}
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask