虽然听起来荒谬.....
我想要一个Constant,每次使用它时它会增加1
int x;
int y;
x = INCREMENTING_CONSTANT;
y = INCREMENTING_CONSTANT;
Run Code Online (Sandbox Code Playgroud)
其中x == 1; 和y == 2
注意我不希望y = INCREMENTING_CONSTANT + 1类型的解决方案.
基本上我想用它作为编译时唯一ID(通常它不会在代码中使用,例如在另一个宏中)
您可以使用Boost.Preprocessor(与C一起使用)和 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
Run Code Online (Sandbox Code Playgroud)
翻译成你想要的
#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
Run Code Online (Sandbox Code Playgroud)
您也可以使用插槽(稍微更灵活,代价是比上述解决方案更多的代码):
#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
Run Code Online (Sandbox Code Playgroud)
Tim*_*Tim -4
嗯,那么它就不是恒定的,是吗?;)
您可以使用一个函数来做到这一点:
int id() {
static int i = 0;
return ++i;
}
x = id();
y = id();
Run Code Online (Sandbox Code Playgroud)
如图所示,这不是线程安全的。为此,您需要使用互斥锁来保护它,或者使用编译器/特定于平台的原子增量器。