Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

incremented define?

Is there anyways to have a define increment every time you use it?

For example

int a = ADEFINE;
int b = ADEFINE;

a is 1 and b is 2.

like image 293
user230821 Avatar asked Dec 04 '22 13:12

user230821


2 Answers

You can use __COUNTER__, though it's not standard. Both MSVC++ and GCC support it.


If you can use boost, the pre-processor library has an implementation of counter. Here's the example from the documentation:

#include <boost/preprocessor/slot/counter.hpp>

BOOST_PP_COUNTER // 0

#include BOOST_PP_UPDATE_COUNTER()

BOOST_PP_COUNTER // 1

#include BOOST_PP_UPDATE_COUNTER()

BOOST_PP_COUNTER // 2

#include BOOST_PP_UPDATE_COUNTER()

BOOST_PP_COUNTER // 3

(Kudo's to gf)

like image 113
GManNickG Avatar answered Dec 24 '22 09:12

GManNickG


If you don't need compile-time-constants, you could do something like this to enumerate classes:

int counter() {
    static int i = 0;
    return i++;
}

template<class T>
int id() { 
    static int i = counter();
    return i; 
};

class A {};
class B {};

int main()
{
    std::cout << id<A>() << std::endl;
    std::cout << id<B>() << std::endl;
}
like image 44
Georg Fritzsche Avatar answered Dec 24 '22 08:12

Georg Fritzsche