Choose generic at compile time

Suppose I have a type A<T> that depends on type T and want to use cargo features to decide T at compile time.

I could do something like

#[cfg(feature = "a")]
 let s = A<i64>
 #[cfg(feature = "b")]
 let s = A<bool>

and so on. However this is not very efficient once I have many types that all depend on T, like
A1, ... A100
Is there a cleaner way to do this for many types? Maybe a macro, or better some type definition. Something like

#[cfg(feature = "a")]
type T = i64
 #[cfg(feature = "b")]
type T = bool

and then I can just use T everywhere...

Have you tried this? I think it should work...

Like this maybe:

#[cfg(feature = "a")]
type TheT = f64;
#[cfg(feature = "b")]
type TheT = bool;

struct A1_<T>(...);
struct A2_<T>(...);

type A1 = A1_<TheT>;
type A2 = A2_<TheT>;

Or alternatively you can hack it with default type parameters:

#[cfg(feature = "a")]
type TheT = f64;
#[cfg(feature = "b")]
type TheT = bool;

// this makes TheT the *default* T, so that when
// somebody just writes A1, it becomes A1<TheT>
struct A1<T = TheT>(...);
struct A2<T = TheT>(...);

That said, it looks like you are creating mutually exclusive features here. These are generally discouraged and you may want to seek an alternative design. (see e.g. this recent discussion).

4 Likes

Lol... Sorry, yes it works. Should I delete this question?

Nah, nah. The more threads, the merrier I say. This isn't Stack overflow. :upside_down_face:

Besides, maybe somebody else has something they'd like to add, too.

7 Likes