I'd like to avoid assigning an Id
to all my Classes where an Id
is needed, so I wrote a small templated id generator.
BaseIdGenerator::makeUniqueId
simply returns a new Id
, everytime it is called:
class BaseIdGenerator {
protected:
static inline Id makeUniqueId() {
static Id nextId = 0;
return nextId++;
}
};
For assigning an Id
to individual classes, the class is simply passed as a template argument to IdGenerator
:
template <typename T>
Id getId();
template <typename T>
class IdGenerator final : public BaseIdGenerator {
static Id id;
template <typename Type>
friend Id getId();
};
template <typename T>
inline Id getId() {
return IdGenerator<T>::id;
}
template <typename T>
Id IdGenerator<T>::id = IdGenerator<T>::makeUniqueId();
This will call makeUniqueId()
exactly one time per class (even at multithreaded applications since C++11 due to the thread safe local static variables)
In action this looks like this:
int main() {
std::cout << getId<int>() << std::endl; // prints 0
std::cout << getId<bool>() << std::endl; // prints 1
std::cout << getId<char>() << std::endl; // prints 2
}
This works as expected.
- Is this well defined behavior in C++?
- Will many uses of
getId()
break this functionality? (Multiple source files etc.) - Is this behavior standardized, so on every machine the output will be the same and in a network application it will work as expected?