开发者

incremented define?

开发者 https://www.devze.com 2022-12-17 01:50 出处:网络
Is there anyways to have a define increment every开发者_开发技巧 time you use it? For example int a = ADEFINE;

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.


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)


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;
}


static int PUT_AN_UNUSED_NAME_HERE = 0;
#define ADEFINE (++PUT_AN_UNUSED_NAME_HERE)


Why not use __LINE__? It's standard C89/C99/C++.

0

精彩评论

暂无评论...
验证码 换一张
取 消