I have a set of C++ classes and each one must declare a unique sequential id as a compile-time constant.
For that I'm using the __COUNTER__
built-in macro which translates to an integer that is incremented for every occurrence of it. The ids need not to follow a strict order. The only requirement is that they are sequential and start from 0:
class A {
public:
enum { id = __COUNTER__ };
};
class B {
public:
enum { id = __COUNTER__ };
};
// etcetera ...
My question is: Is there a way to achieve the same result using a C++ construct, such as templates?
Here is a possible way to do it using __LINE__
macro and templates:
template <int>
struct Inc
{
enum { value = 0 };
};
template <int index>
struct Id
{
enum { value = Id<index - 1>::value + Inc<index - 1>::value };
};
template <>
struct Id<0>
{
enum { value = 0 };
};
#define CLASS_DECLARATION(Class) \
template <> \
struct Inc<__LINE__> \
{ \
enum { value = 1 }; \
}; \
\
struct Class \
{ \
enum { id = Id<__LINE__>::value }; \
private:
Example of using:
CLASS_DECLARATION(A)
// ...
};
CLASS_DECLARATION(B)
// ...
};
CLASS_DECLARATION(C)
// ...
};
See live example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With