1

I have code similar to the following:

fn f1<const B: bool>(x:u64) { }

fn f2<const B: bool>(x:u64) {
    match B {
        true => f1::<false>(x),
        false => f1::<true>(x),
    }
}

That is, I need to negate a const bool in function calls. Rust currently doesn't support something as plain as f1::<!B>() unfortunately. Is there a better way for me to do this other than to litter match statements everywhere?

2 Answers2

0

If this is just one function, I would create a function:

fn negate_f1<const B: bool>(x: u64) {
    match B {
        true => f1::<false>(x),
        false => f1::<true>(x),
    }
}

fn f2<const B: bool>(x: u64) {
    negate_f1::<B>(x);
}

If more, you can create a macro. The following macro works only for bare identifiers (foo(), not foo::bar()) and one generic parameter, extending it is difficult but possible:

macro_rules! negate {
    ( $fn:ident :: < ! $param:ident > ( $($arg:expr),* $(,)? ) ) => {
        match $param {
            true => $fn::<false>( $($arg),* ),
            false => $fn::<true>( $($arg),* ),
        }
    }
}

fn f2<const B: bool>(x: u64) {
    negate!(f1::<!B>(x));
}
Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
0

On nightly, this can be achieved by enabling the generic_const_exprs feature and wrapping the constant expression in curly braces: f1::<{!B}>. However due to this bug this requires extra bounds on f2:

#![feature(generic_const_exprs)]

fn f1<const B: bool>(_x:u64) { }

pub fn f2<const B: bool>(x:u64) where [(); !B as usize]: {
    f1::<{!B}>(x);
}

Playground

Jmb
  • 18,893
  • 2
  • 28
  • 55