I think it's better to eliminate count function altogether and put the
count functionality into class/struct such as, in your case, reg_base.
struct counter{
static unsigned int count getId(return id++;)
private:
static unsigned int id;
};
unsigned int counter::id=0;
Or some cleaner variation of that. I don't like member-less function
in the code. At the very least, we ought to namespace it if we're to
have this function, given that it's short to use and easier to code
than an alternative I've just mentioned.
Yup. Also, get_id() wasn't const. Here is a cleaner version:
class reg_base {
protected:
static
unsigned int
count ( void ) {
static unsigned int c = 0;
return ( c++ );
}
public:
virtual
unsigned int get_id ( void ) const = 0;
virtual
~reg_base ( void ) {}
};
template < typename D >
class reg : public reg_base {
static unsigned int const the_id;
public:
unsigned int get_id ( void ) const {
return ( the_id );
}
static
unsigned int id ( void ) {
return ( the_id );
}
virtual
~reg ( void ) {}
};
template < typename D >
unsigned int const reg<D>::the_id = reg<D>::reg_base::count();
struct X : public reg<X> {};
struct Y : public reg<Y> {};
#include <iostream>
int main ( void ) {
X x;
Y y1;
Y y2;
reg_base * px = new X ();
reg_base * py = new Y ();
std::cout << "X " << x.get_id() << '\n';
std::cout << "Y " << y1.get_id() << '\n';
std::cout << "Y " << y2.get_id() << '\n';
std::cout << "X " << px->get_id() << '\n';
std::cout << "Y " << py->get_id() << '\n';
std::cout << "X " << X::id() << '\n';
std::cout << "Y " << Y::id() << '\n';
delete ( px );
delete ( py );
}
Yes, I tried it and it is indeed what I need. Only what I also need
already registered.
But what I need most now is a crash course on templates ;-).