#include <iostream>
template< class T, unsigned S >
struct my_iterator;
template< class T >
struct my_iterator< T, 1 >
{
T* p;
};
template< class T, unsigned S >
struct my_iterator : my_iterator< T, S / 2 >
{
static_assert ((S & (S - 1)) == 0, "S must be a power of 2");
using my_iterator< T, S / 2 >::p;
unsigned burp() {return (*p) + S;}
};
int main()
{
int v = 10;
my_iterator< int, 8 > a;
a.p = &v;
std::cout << a.burp() << std::endl;
my_iterator< int, 4 >& b = a;
std::cout << b.burp() << std::endl;
my_iterator< int, 1 > c;
c.p = &v;
std::cout << c.burp() << std::endl; // error: no member named 'burp'
return 0;
}
This will fix the error:
template< class T >
struct my_iterator< T, 1 >
{
unsigned burp() {return (*p) + 1;}
T* p;
};
but in my real code I have many methods, not just burp
, all dependent on S
and p
, that would all need to be implemented twice, once in the general class and once in the specialization. Is there any way to avoid the duplicate code? I saw this similar question:
Avoiding code duplication in a specialized template
but the answer will not work in my case because I'll end up with many copies of p
, one at each level of the recursive hierarchy.