Unique ID Defined by Most-Derived Class accessible through Base Class
Posted
by Narfanator
on Stack Overflow
See other posts from Stack Overflow
or by Narfanator
Published on 2010-03-17T22:58:56Z
Indexed on
2010/03/17
23:01 UTC
Read the original article
Hit count: 418
c++
|inheritance
Okay, so, the idea is that I have a map of "components", which inherit from componentBase, and are keyed on an ID unique to the most-derived*.
Only, I can't think of a good way to get this to work. I tried it with the constructor, but that doesn't work (Maybe I did it wrong). The problem with any virtual, etc, inheritance tricks are that the user has to impliment them at the bottom, which can be forgotten and makes it less... clean.
*Right phrase? If -> is inheritance; foo is most-derived: foo->foo1->foo2->componentBase
Here's some code showing the problem, and why CRTP can't cut it: (No, it's not legit code, but I'm trying to get my thoughts down)
#include<map>
class componentBase
{ public: virtual static char idFunction() = 0; };
template <class T>
class component
: public virtual componentBase
{
public:
static char idFunction(){ return reinterpret_cast<char>(&idFunction); }
};
class intermediateDerivations1
: public virtual component<intermediateDerivations1>
{
};
class intermediateDerivations2
: public virtual component<intermediateDerivations2>
{ };
class derived1
: public intermediateDerivations1
{ };
class derived2
: public intermediateDerivations1
{ };
//How the unique ID gets used (more or less)
std::map<char, componentBase*> TheMap;
template<class T>
void addToMap(componentBase * c)
{
TheMap[T::idFunction()] = c;
}
template<class T>
T * getFromMap()
{
return TheMap[T::idFunction()];
}
int main()
{
//In each case, the key needs to be different.
//For these, the CRTP should do it:
getFromMap<intermediateDerivations1>();
getFromMap<intermediateDerivations2>();
//But not for these.
getFromMap<derived1>();
getFromMap<derived2>();
return 0;
}
More or less, I need something that is always there, no matter what the user does, and has a sortable value that's unique to the most-derived class.
Also, I realize this isn't the best-asked question, I'm actually having some unexpected difficultly wrapping my head around it in words, so ask questions if/when you need clarification.
© Stack Overflow or respective owner