I am writing a constexpr function and need to use a constexpr for. The loop can be manually expanded out by hand but I find that ugly in code and redundant.
How can I make a "constexpr for"?
Should I make a helper class? If so, how would I go about writing something like this:
#define for_constexpr( TYPE, VAR, START, CONDITION, END_OP, BODY ) \
for_constexpr_helper< \
TYPE, START, // TYPE START = 0; \
[ ]( TYPE VAR ) constexpr { return CONDITION; }, \
[ ] constexpr { END_OP; }, \
[ & ]( TYPE VAR ) constexpr { BODY; } >( )
Where the usage is something like
int x = 0;
for_constexpr( int, i, 0, i < 3, ++i, x += i * 2 );
More specifically, how can I use i in a constexpr context, such as a template parameter?
What are my options?
Example code:
auto ret = 0;
for ( int i = 0; i < 3; ++i )
{
static_assert( i != 4 ); // just an example
ret += i;
}
return ret;
This fails to be constexpr. Ugly example:
auto ret = 0;
ret += 1;
ret += 2;
ret += 3;
return ret; // works
constexprfunctions can already use for loops. What do you need out of it that it isn't giving you?ias a template parameter;