jonnie
jonnie

Reputation: 101

C++ Access numbered variables

We have numbered variables like:

float my_float_0;
float my_float_1;
float my_float_2;

Is there any form of template / macro magic that would let us access these variables by index in a for loop?

Upvotes: 0

Views: 65

Answers (1)

Vittorio Romeo
Vittorio Romeo

Reputation: 93274

If you have no control over the variables, your only option is some good ol' macro metaprogramming. Boost.Preprocessor's documentation is a good place to start - you can iterate over a range of numbers and concatenate them with the my_float_ token to produce your variable names.

Example (untested):

#define SEQ (0)(1)(2)
#define MACRO(r, data, elem) BOOST_PP_CAT(elem, data)

BOOST_PP_SEQ_FOR_EACH(MACRO, my_float_, SEQ) 
// expands to my_float_0 my_float_1 my_float_2

By changing what MACRO expands to, you can generate code for each variable.

Upvotes: 1

Related Questions