I have a base class called Component
which has a number of classes derived from it. I want each class to have an integer associated with it (doesn't matter which component gets what value, as long as they start at 0 and are contiguous). I don't know how to do this directly, so in the same file as Component
I added the following:
template <typename T>
class ComponentIdentifier
{
public:
static unsigned int cid;
};
static unsigned int CIDCounter = 0;
template <typename T> unsigned int ComponentIdentifier<T> = CIDCounter++;
template <typename T> unsigned int ComponentID()
{
return ComponentIdentifier<T>::cid;
}
unsigned int ComponentCount(); // Defined in .cpp file, just returns CIDCounter
Now I tested the ComponentID() function and it appears to work fine. Each component class that I tried ComponentID on returned a different integer just as I expected. However, whenever I call ComponentCount I get 0.
e.g. if I have the following lines of code:
std::cout << ComponentID<AAA>() << std::endl;
std::cout << ComponentID<BBB>() << std::endl;
std::cout << ComponentID<CCC>() << std::endl;
std::cout << ComponentCount() << std::endl;
then my output is:
0
1
2
0
I suspect what's happening is that CIDCounter is being set to 0 again after its used to set the cid's of each component, but I don't know for sure and that seems kind of weird. Is there a way to do what I want or am I crazy and this whole plan doomed to failure?