This is the first of a hopefully long series of threads where we’ll take some C/C++ macros used by real application and try to find the equivalent (or perhaps better) solution using Zig. The aim is not to replicate the exact behavior of the C code. Generally that’s not possible. The preprocessor just works differently. The aim is to solve the actual problem at hand. I suspect that we’ll often need to take very different approaches.
The present example is case in point. BOOST_PP_COUNTER is a macro that yield a incrementing number. Simple enough and yet impossible to implementing using comptime programming due to the difference in execution order (among other things). What we can implement though is a comptime counter, something that yields a new number everytime it’s invoked at comptime. So that’s what’s we’re aiming for here.
For you convenience I’ve posted the documentation for BOOST_PP_COUNTER below:
The BOOST_PP_COUNTER macro expands to the current counter value.
Usage
BOOST_PP_COUNTER
Remarks
This macro expands to an integer literal. Its initial value is 0
. Between usages of BOOST_PP_UPDATE_COUNTER, the value of BOOST_PP_COUNTER is constant.
See Also
Requirements
Header: <boost/preprocessor/slot/counter.hpp>
Sample Code
#include <boost/preprocessor/slot/counter.hpp>
constexpr int A = BOOST_PP_COUNTER; // 0
#include BOOST_PP_UPDATE_COUNTER()
constexpr int B = BOOST_PP_COUNTER; // 1
#include BOOST_PP_UPDATE_COUNTER()
constexpr int C = BOOST_PP_COUNTER; // 2
#include BOOST_PP_UPDATE_COUNTER()
constexpr int D = BOOST_PP_COUNTER; // 3
EDIT: Modified sample code to make usage clearer