3

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 ifs 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.

MaPo
  • 613
  • 4
  • 9

1 Answers1

4

You can use simple ifs. There is almost no chance the optimizer will not elide a const if false or if true. The only advantage of if constexpr in C++ is that you can put things that will not compile there if the expression evaluates to false.

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
  • Thank you for the answer. I imagined that the compiler was able to optimize. I was wandering if there was something more robust and less compiler-dependent. – MaPo Jul 24 '22 at 14:37