Replicate this c++ code to rust


Please have a look at this extremely simplified C++ code which is required for my app. Please keep in mind the real code has a lot more going on.

Here the template pass two i32 as template parameters. This will be later used to read memory chunks with a proper layout.

I avoided a lot of other mechanisms at play like concepts in this example. But the chain of logic is not shallow and it has been done that way for reasons because we need those if constexpr that expand deeper, and because we like specialisation (opinion, hey, we are humans).

The idea is to have the compiler have the maximum information to create branchless blocks, as much as possible, by giving it as much info at compile time as possible.

Now, in Rust we have const generics, but I fear my example still relies on specialisation, hence the error.

What would be the cleanest way to do it in Rust, currently. We can use nightly, no issue but if we have to wait we will.

Please don't give me the final code, just keywords instead. It will point me in the right direction and I will try by myself. :nerd_face:


The first thing to note is that your C++ version doesn't call the specialized function. (I don't understand why, but quite frankly I'm not willing to either :sweat_smile:)

Instead of any sort of funky specialization, I would just put if statements in the code, similar to how the generic C++ function is laid out, and not worry about it. These comparisons will almost certainly be optimized away when you actually call the function (given that their const generic parameters are known at compile time).

1 Like

Ah my bad, too fast (that tells a lot)

this one does

Ok, so I will keep it that way then

and let it go :+1:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.