Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ construct that behaves like the __COUNTER__ macro [duplicate]

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?

like image 269
glampert Avatar asked Dec 26 '22 10:12

glampert


1 Answers

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.

like image 194
Constructor Avatar answered Jan 13 '23 12:01

Constructor