Using C++ template and if constexpr
I found a trick that I like a lot: suppose you have a function with some tunable option that are known compile-time, I can write something like
template <bool Op1, bool Op2, bool Op3>
void my_func()
{
...
if constexpr (Op1) {
...
} else {
...
}
... //similar (possibly even nested) constexpr
}
Now I think that this is rather convenient in term of the line of code you save (with n options one has 2^n different functions) and also in term of performance, since these if
s are evaluated compile-time (suppose for instance this function is called many times via a delegate in a loop). In practice, during the compilation 2^n replicas of this function are created with all the options.
I'm very interested in doing something similar with Rust. I noticed that generic parameters are already there, but I'm not sure about an equivalent of if constexpr
.
Of course I would be please to find an other, more rust-ic solutions with the same requirements: no unnecessary run-time if, no copy-paste code.