使用宏编写const泛型枚举组合



考虑一个具有两个const泛型参数的toy结构:

pub struct Foo<const N: usize, const M: usize>([usize; N], [usize; M]);
impl<const N: usize, const M: usize> Foo<N, M> {
pub fn bar(&self) -> usize {
N * M
}
}

假设NM在1和5之间的所有组合都是允许的,因此我们可以编写以下枚举:

pub enum FooEnum {
Foo_1_1(Foo<1, 1>),
Foo_1_2(Foo<1, 2>),
Foo_2_1(Foo<2, 1>),
Foo_2_2(Foo<2, 2>),
// ... and so on.
}
impl FooEnum {
pub fn bar(&self) -> usize {
match self {
Self::Foo_1_1(x) => x.bar(),
Self::Foo_1_2(x) => x.bar(),
Self::Foo_2_1(x) => x.bar(),
Self::Foo_2_2(x) => x.bar(),
// ... and so on.
}
}
}

我的问题是:我们是否可以编写一个声明性宏来生成它,而无需手动写出所有组合?也就是说,类似于impl_foo_enum!(1, 2, 3, 4, 5),而不是impl_foo_enum!(1;1, 1;2, 1;3, [...and so on])


我可以使用paste机箱编写后一个宏:

macro_rules! impl_foo_enum {
($($n:literal;$m:literal),+) => {
paste::paste! {
pub enum FooEnum2 {
$(
[<Foo _ $n _ $m>](Foo<$n, $m>)
),+
}
impl FooEnum2 {
pub fn bar(&self) -> usize {
match self {
$(Self::[<Foo _ $n _ $m>](x) => x.bar()),+
}
}
}
}
}
}
impl_foo_enum!(1;1, 1;2, 2;1, 2;2);

(游乐场(

为了获得一个不那么乏味的宏,有几个相关的问题和有用的答案(1,2(,我认为我可以适应,但在这两种情况下,函数调用都可以在宏中重复,这似乎可以简化事情。例如,使用第一个链接示例中的方法,我开始:

macro_rules! for_all_pairs {
($mac:ident: $($x:literal)*) => {
for_all_pairs!(@inner $mac: $($x)*; $($x)*);
};
(@inner $mac:ident: ; $($x:literal)*) => {};
(@inner $mac:ident: $head:literal $($tail:literal)*; $($x:literal)*) => {
$(
$mac!($head $x);
)*
for_all_pairs!(@inner $mac: $($tail)*; $($x)*);
};
}
macro_rules! impl_foo_enum {
($n:literal $m:literal) => {
paste::paste! { [<Foo _ $n _ $m>](Foo<$n, $m>) }
}
}
pub enum FooEnum3 {
for_all_pairs!(impl_foo_enum: 1 2)
}

(游乐场(

它不编译,因为编译器不希望在枚举变量位置有宏(我相信(。

(需要明确的是,我不一定想把上面的内容用于任何严重的事情,我只是在实验时遇到了它,并感到好奇。(

开始:

#![allow(non_camel_case_types)]
pub struct Foo<const N: usize, const M: usize>([usize; N], [usize; M]);
impl<const N: usize, const M: usize> Foo<N, M> {
pub fn bar(&self) -> usize {
N * M
}
}
macro_rules! impl_foo_2{
($($n:literal)*) => {
impl_foo_2!([] @orig($($n)*) ($($n)*) ($($n)*));
};
(
[$(($n:literal $m:literal))*]
@orig($($n_orig:literal)*)
($($n_unused:literal)*) ()
) => {
paste::paste! {
pub enum FooEnum2 {
$([<Foo _ $n _ $m>](Foo<$n, $m>)),+
}
impl FooEnum2 {
pub fn bar(&self) -> usize {
match self {
$(Self::[<Foo _ $n _ $m>](x) => x.bar()),+
}
}
}
}
};
(
[$($t:tt)*]
@orig($($n_orig:literal)*)
() ($m0:literal $($m:literal)*)
) => {
impl_foo_2!(
[$($t)*]
@orig($($n_orig)*)
($($n_orig)*) ($($m)*)
);
};
(
[$($t:tt)*]
@orig($($n_orig:literal)*)
($n0:literal $($n:literal)*) ($m0:literal $($m:literal)*)
) => {
impl_foo_2!(
[$($t)* ($n0 $m0)]
@orig($($n_orig)*)
($($n)*) ($m0 $($m)*)
);
}
}
impl_foo_2!(1 2 3 4 5);

impl_foo_2在内部生成两个相同的号码列表副本。然后,它继续一次处理一个m,并将其与每个n组合(它通过反复切断第一个n来做到这一点(。如果n-列表用完,它会重置n-列表,并截断第一个m。所有这些都被完成,直到所有的CCD_ 13和CCD_。

中间结果被收集到宏的第一个参数中,该参数在最后被传递给impl_foo_enum

最新更新