I have a feature that requires adding a bound to many functions. Something like this:
fn function<T>(_: &T)
where
T: SomeTrait
{}
Without the feature I do not want that bound. Right now the only way I know how to make this happen is by coping the function twice:
#[cfg(not(feature="add_bound"))]
fn function<T>(_: &T) {}
#[cfg(feature="add_bound")]
fn function<T>(_: &T)
where
T: SomeTrait
{}
But this requires loads of code duplication. There should be a way to do this better. Is there?
I think I could do this:
trait MaybeBounds {}
#[cfg(feature="add_bound")]
impl<T: SomeTrait> MaybeBounds for T {}
#[cfg(not(feature="add_bound"))]
impl<T> MaybeBounds for T {}
fn function<T>(_: &T)
where
T: MaybeBounds
{}
Or like:
#[cfg(feature="add_bound")]
trait MaybeBounds: SomeTrait {}
#[cfg(not(feature="add_bound"))]
trait MaybeBounds {}
But that would make the function signatures maybe misleading. Is this the only way to do it? (other than macros )
You could
#[inline(always)]
fn _function<T>(_: &T) {
same_innards()
}
#[cfg(not(feature="add_bound"))]
pub fn function<T>(a: &T) {
_function(a)
}
#[cfg(feature="add_bound")]
pub fn function<T>(a: &T) where T: SomeTrait {
_function(a)
}
That makes it better if the function bodies are big but in this case, imagine loads of small functions.
It would be good if something like this would be possible:
fn function<T>(_: &T)
where
#[cfg(feature="add_bound")]
T: SomeTrait
{}
If the bounds are simple enough, you can
pub fn function<
#[cfg(feature="add_bound")] T: SomeTrait,
#[cfg(not(feature="add_bound"))] T,
>(_: &T) {
}
I don't know if there are any specific reasons for not accepting attributes on where clause items.
1 Like
This works! Thank you very much.
system
Closed
October 14, 2021, 10:06pm
7
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.