Re: code duplication in template specialization
* Christof Warlich:
I just need a specialization for only one member function of a template
class with _many_ members. Do I really have to duplicate the source code
for all the members, i.e. for those that do not need to be specialized?
No.
E.g. in the example below, I'd like to avoid to redefine member B::g():
#include <stdio.h>
template<int x, typename T, short y> class B {
public:
void f(void) {printf("generic f()\n");}
void g(void) {printf("generic g()\n");}
};
// specialization for T == float
template<int x, short y> class B<x, float, y> {
public:
void f(void) {printf("specialized f()\n");}
void g(void) {printf("generic g()\n");}
};
int main(void) {
B<1, int, 2> b;
b.f();
b.g();
B<1, float, 2> s;
s.f();
s.g();
}
Thanks for any suggestions,
template< int x, typename T, short y >
class B
{
public:
void f() { say( "generic f()" ); }
void g() { G<x, T, y>::do( *this ); }
};
template< int x, typename T, short y >
struct G
{
static void do( B<x, T, y> const& ) { say( "generic g()\n" ); }
};
template< int x, short y >
struct G<x, float, y>
{
static void do( B<x, float, y> const& ) { say( "g<float>()\n" ); }
}
Or thereabouts -- untested code.
Depending on your actual problem some other refactoring may be much better.
Cheers, & hth.,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?