incremented define?

 ̄綄美尐妖づ 提交于 2019-12-19 09:04:26

问题


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.


回答1:


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



回答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)




回答3:


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



回答4:


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



来源:https://stackoverflow.com/questions/2076757/incremented-define

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!