检查宏中定义的项目中的功能标志

Check a feature flag in an item defined in a macro

目前我有一个看起来像这样的板条箱:

trait TestTrait {}

macro_rules! add_trait {
    ($type:ident) => {
        #[cfg(feature="my-feature")]
        impl TestTrait for $type {}
    }
}

如本板条箱的单元测试中所写,这工作正常。但是,当我在我的应用程序中实际使用 crate 作为依赖项时,在启用功能标志的情况下,特征是 not 添加;我相信,因为 [cfg(feature="my-feature")] 是在我的应用程序的上下文中评估的,它没有这样的功能标志。查看宏扩展代码,impl TestTrait ... 项不存在,即使宏的其他部分(与这个最小示例无关)也存在。

有没有办法让它工作?例如,是否有某种 [cfg(feature="my-crate::my-feature")] 语法?如果不是,我应该如何在宏上下文中启用基于创建范围功能标志的条件编译?

I believe because the [cfg(feature="my-feature")] is evaluated in the context of my application, which has no such feature flag.

是的,完全正确。

您可以将功能标志放在宏本身上,然后多次定义它:

#[cfg(feature="my-feature")]
macro_rules! add_trait {
    ($type:ident) => {
        impl TestTrait for $type {}
    }
}

#[cfg(not(feature="my-feature"))]
macro_rules! add_trait {
    ($type:ident) => {}
}