3
\$\begingroup\$

I could not find a compile time counter/accumulator to achieve something like the following:

#define DECLARE_VAR(type, varName) \
   type varName;                   \
   ADD_TO_ACCUMULATOR(sizeof(type));

DECLARE_VAR(float, var1);
DECLARE_VAR(bool, var2);
constexpr int total = GET_ACCU_AND_ADD(0);
static_assert(total == 5);

So I came up with the following:

#define GET_ACCU_AND_ADD_IMPL(number, counterIndex)     \
    summer<counterIndex>::get();                          \
        template<>                                        \
    struct summer<counterIndex+1> {                        \
        constexpr static int get() {                        \
            return summer<counterIndex>::get() + (number);  \
        }                                                     \
    };                                                        

#define ADD_TO_ACCUMULATOR_IMPL(number, counterIndex)     \
        template<>                                        \
    struct summer<counterIndex+1> {                        \
        constexpr static int get() {                        \
            return summer<counterIndex>::get() + (number);  \
        }                                                     \
    }; 

#define GET_ACCU_AND_ADD(number) \
    GET_ACCU_AND_ADD_IMPL(number, __COUNTER__)

#define ADD_TO_ACCUMULATOR(number) \
    ADD_TO_ACCUMULATOR_IMPL(number, __COUNTER__)


template<int tIndex>
struct summer {
    constexpr static int get() {
        static_assert(tIndex == 0, "should not be called/instantiated");
        return 0;
    }
};

template<>
struct summer<0> {
    constexpr static int get() {
        return 0;
    }
};

Downsides:

  • Relies on __ COUNTER __
  • ?

Feedback is appreciated, maybe there are already better solutions out here?

\$\endgroup\$

closed as off-topic by papagaga, Donald.McLean, Sᴀᴍ Onᴇᴌᴀ, IEatBagels, Graipher Jan 23 at 21:04

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Lacks concrete context: Code Review requires concrete code from a project, with sufficient context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site." – papagaga, Donald.McLean, Sᴀᴍ Onᴇᴌᴀ, IEatBagels, Graipher
If this question can be reworded to fit the rules in the help center, please edit the question.