Equivalent of C++ typed template parameters

Hi, I am working on a library, I'd like to do something like the following in Rust:

template <size_t param>
class A {
public:
  void method(void) {
    // uses `param` which gets inlined.
  }
};

Probably, it has been asked before but I can't find anything related. What's the best way to approach this? Is it using macro_rules? Are there any libraries that I could take a look at that do something similar?

We are working on const generics, which is a similar feature to this. It's not ready for prime time though; an initial implementation is in nightly, but there's a lot more work to do.

1 Like

It's ugly at the moment.

use std::marker::PhantomData;

trait Param {
    const PARAM:usize;
}

struct A<T:Param> { _param: PhantomData<T> }
impl<T:Param> A<T> {
    fn method(&self) {
        println!("{}", T::PARAM);
    }
}

struct ONE;
impl Param for ONE {
    const PARAM:usize = 1;
}

fn main() {
    let a: A<ONE> = A{ _param: PhantomData };
    a.method();
}
1 Like

Hi, thanks a lot, this is exactly what I am referring to! I guess macros are not the best way to solve this.

Thanks for the reply! I have tried something similar using an enum instead of a struct ONE in a case where PARAM was taking a small number of values. If I understand correctly this uses the type (struct ONE) to do specialization and not the PARAM's value.

Each value should be a separate type for this to work. You can use typenum which already implements this.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.