你可以让一个递增的编译器常数? [英] Can you make an incrementing compiler constant?
问题描述
虽然听起来荒谬的......
While sounding nonsensical.....
我要一个常量,每一个使用它时它会递增1
I want a Constant where every time you use it it will increment by 1
int x;
int y;
x = INCREMENTING_CONSTANT;
y = INCREMENTING_CONSTANT;
其中x == 1;和y == 2
where x == 1; and y == 2
请注意,我不想Y = INCREMENTING_CONSTANT + 1型的解决方案。
Note I don't want y = INCREMENTING_CONSTANT+1 type solutions.
基本上我想使用它作为一个编译时唯一的ID(通常它不会在code类的例子,但另一个宏内部使用)
Basically I want to use it as a compile time unique ID ( generally it wouldn't be used in code like the example but inside another macro)
推荐答案
您可能能够使用Boost装上去在一起。preprocessor(用C厂)和 BOOST_PP_COUNTER
You may be able to put something together using Boost.Preprocessor (Works with C) and BOOST_PP_COUNTER
#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
翻译成你想要的东西。
Translated into what you want
#include <boost/preprocessor/slot/counter.hpp>
int x = BOOST_PP_COUNTER; // 0
#include BOOST_PP_UPDATE_COUNTER()
int y = BOOST_PP_COUNTER;// 1
#include BOOST_PP_UPDATE_COUNTER()
int z = BOOST_PP_COUNTER; // 2
您也可以使用插槽(以更code的成本比上述方案更灵活一点):
You could also use slots (slightly more flexible at the cost of more code than the above solution):
#include <boost/preprocessor/slot/slot.hpp>
#define BOOST_PP_VALUE 0 //ensure 0 to start
#include BOOST_PP_ASSIGN_SLOT(1)
int a = BOOST_PP_SLOT(1); //0
#define BOOST_PP_VALUE 1 + BOOST_PP_SLOT(1)
#include BOOST_PP_ASSIGN_SLOT(1)
int b = BOOST_PP_SLOT(1); //1
这篇关于你可以让一个递增的编译器常数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!