你可以让一个递增的编译器常数? [英] Can you make an incrementing compiler constant?

查看:167
本文介绍了你可以让一个递增的编译器常数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然听起来荒谬的......

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆