这只是伪代码:
macro_rules! attribute {
$e: expr<f32> => { /* magical float stuff */ };
$e: expr<i64> => { /* mystical int stuff */ };
};
Run Code Online (Sandbox Code Playgroud)
我希望有一个不同的扩展宏取决于我传递给宏的类型.
这就是它在C++中的工作方式
template <typename T>
struct Attribute{ void operator(T)() {} };
template <>
struct Attribute<float> {
void operator(float)(float) { /* magical float stuff */ }
};
template <>
struct Attribute<long> {
void operator()(long) { /* mystical int stuff */ }
}
Run Code Online (Sandbox Code Playgroud) 在宏中定义实现时,访问struct成员类型以避免必须将其作为额外参数传递可能很有用.(见这个问题)
impl PartialEq<u32> for MyStruct { ... }
Run Code Online (Sandbox Code Playgroud)
有没有办法在不事先知道它是哪种类型的情况下访问结构成员的类型?
impl PartialEq<typeof(MyStruct.member)> for MyStruct { ... }
Run Code Online (Sandbox Code Playgroud)
如果它有用,这是为什么我有兴趣这样做的缩写示例:
struct_bitflag_impl!(
pub struct MyFlag(u8);,
MyFlag, u8);
// ^^ how to avoid having this extra arg?
// (Used by ``impl PartialEq<$t_internal> for $p``)
// couldn't it be discovered from `MyFlag.0` ?
// the macro
macro_rules! struct_bitflag_impl {
($struct_p_def: item, $p:ident, $t_internal:ty) => {
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
$struct_p_def
impl ::std::ops::BitAnd for $p {
type Output = $p;
fn bitand(self, _rhs: $p) …Run Code Online (Sandbox Code Playgroud)