How to use if-constexpr without repeating code?

I am currently doing:

if constexpr(constexpr_bool_var1) {
    auto arg1 = costly_arg1(); auto arg2 = costly_arg2();
    if (costly_runtime_function(arg1, arg2)) {
        // do X, possibly more constexpr conditions
        // do Y
        // ...
    }
} else {
    // do X, possibly more constexpr conditions
    // do Y
    // ...
}

One possible way is to convert do X / Y, etc. into one doXY () function and calling it in both places, however it seems very cumbersome because I have to write a function that exists only for the convenience of metaprogramming.

I want something like:

if not constexpr(constexpr_bool_var1 && some_magic(costly_runtime_function(arg1, arg2)) {
  // do X, do Y
} 

Another way:

auto arg1 = costly_arg1(); // Unneeded extra work out not within constexpr
auto arg2 = costly_arg2();
if (constexpr_bool_var1 && costly_runtime_function(arg1, arg2)) {
} else {
    // do X, possibly more constexpr conditions
    // do Y
    // ...
}

However, here arg1 and arg2 are declared outside the if condition, so they will be uselessly created.

+4
source share
3 answers

, ; ( costly_runtime_function " X Y" " X Y" ), , , , some_magic. .

- , , , X Y:

bool do_x_y = true;
if constexpr(constexpr_bool_var1) {
    // Maybe we don't actually want X and Y
    auto arg1 = costly_arg1(); auto arg2 = costly_arg2();
    do_x_y = costly_runtime_function(arg1, arg2);
}
if (do_x_y)  {
    // do X, possibly more constexpr conditions
    // do Y
    // ...
}

, , Andrei R. , , , . , , .

+3

. , / .

#include <cstdlib>
#include <utility>

/*
 * simulation
 */
void doX() {}
void doY() {}

int costly_arg1() { return 1; }
int costly_arg2() { return 2; }

bool costly_runtime_function(int, int) { return rand() < RAND_MAX / 2; }

constexpr bool constexpr_bool_var1 = true;

/*
 * A functor that maybe does something
 */
template<class F>
struct maybe_do
{
    constexpr maybe_do(F&& f) : f(std::move(f)) {}

    constexpr void operator()() const 
    {
        if (enabled)
            f();
    }

    constexpr void enable(bool e) {
        enabled = e;
    } 

    F f;
    bool enabled = true;
};

int main()
{
    auto thing = maybe_do{
        [] {
            doX();
            doY();
        }
    };

    if constexpr(constexpr_bool_var1) 
    {
        thing.enable(costly_runtime_function(costly_arg1(), 
                                             costly_arg2()));
    }
    thing();
}
0

:

auto stuff = [&] {
    // do X, possibly more constexpr conditions
    // do Y
    // ...
};

if constexpr(constexpr_bool_var1) {
    auto arg1 = costly_arg1(); auto arg2 = costly_arg2();
    if (costly_runtime_function(arg1, arg2)) {
        stuff();
    }
} else {
    stuff();
}

And if your lambda can receive automatic values, you can also pass a variable of different types from the area if.

0
source

Source: https://habr.com/ru/post/1687404/


All Articles