0

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?

5
  • 1
    The variable names are auto-generated from external; using arrays instead is sadly not an option. Commented Aug 25, 2017 at 12:38
  • 1
    That's what arrays are for. Commented Aug 25, 2017 at 12:39
  • 1
    Why on earth are you not using an array or a vector? Commented Aug 25, 2017 at 12:39
  • 1
    Whatever auto-generated that does not appear to be particularly useful. Commented Aug 25, 2017 at 12:40
  • Naive macro solution: #define MY_FLOAT_(i) my_float_##i for (int i = 0; i <= 2; ++i) MY_FLOAT_(i) = i; Commented Aug 25, 2017 at 12:54

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.