inheriting from template of self

S

Sylvain Audi

Hello,

I have implemented a data managing template class, that takes care of
allocation of objects of type T. It's a simple array of T* that creates
new objects and returns its index so that the objects are handled
through that index.

Now for the fun part. I'm trying to create a template class for the
Managed objects, so that each object knows how to find itself (its index
and the pointer to the manager).

Here's the basic code:

//////////////////////
template <class T>
class Manager
{
public:
int CreateObject();
void DestroyObject( int idx );
(...)
private:
std::vector<T*> m_apObjects;
};

//////////////////////

template <class T>
class ManagedObject
{
public:
(...)
private:
typedef Manager<T> MyManagerType;

MyManagerType* m_pMgr;
int m_nIndex;
};

//////////////////////

My problem is that this whole concept implies creating "managed object"
classes that derive from a template of itself :
class MyManagedObj : public ManagedObject<MyManagedObj> {...};

This is not exactly the kind of code I like to write, as it looks pretty
tricky. Also, I have no idea if that is even legal c++ (vc6 anc vc7
accept it though).

Any suggestion / advices?
Thanks,

Sylvain.
 
P

Pavel Vozenilek

Sylvain Audi said:
My problem is that this whole concept implies creating "managed object"
classes that derive from a template of itself :
class MyManagedObj : public ManagedObject<MyManagedObj> {...};

This is not exactly the kind of code I like to write, as it looks pretty
tricky. Also, I have no idea if that is even legal c++ (vc6 anc vc7 accept
it though).
Yes, it is legal and useful. It is called Curiously Recurring Template
Pattern (CRTP).

It could be used to simulate polymorphism w/o overhead
of virtual functions (under certain circumstances).

/Pavel
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,201
Messages
2,571,049
Members
47,655
Latest member
eizareri

Latest Threads

Top