I am trying to use ?
in a macro, matching an arbitrary keyword:
#![feature(macro_at_most_once_rep)]
macro_rules! foo {
(
pub fn $name:ident (
& $m : $( mut )? self
)
) => (
pub fn $name (
& $m self
) {}
)
}
struct Foo;
impl Foo {
foo!( pub fn bar(&mut self) );
foo!( pub fn baz(&self) );
}
fn main() {}
I tried varied syntax, but they all failed. How to do this?
To create a macro with arguments, put them in parentheses separated by commas after the macro name, e.g. then BadSquare(3+4) would give 3+4*3+4, which evaluates to 19, which is probably not what we intended.
Keyword parameters are symbolic parameters that can be specified in any order when the macro is called. The parameter will be replaced within the macro body by the value specified when the macro is called. These parameters can be given a default value.
Macro names should only consist of alphanumeric characters and underscores, i.e. 'a-z' , 'A-Z' , '0-9' , and '_' , and the first character should not be a digit.
The key to making this work is a new pre-processor feature in C++20, __VA_OPT__(x) , which expands to x when a variable-argument macro has more than zero arguments and to nothing otherwise.
One trick would be to insert a repetition with a dummy token.
#![feature(macro_at_most_once_rep)]
macro_rules! foo {
(
pub fn $name:ident (
& $( $(@$m:tt)* mut )? self
)
) => (
pub fn $name (
& $( $(@$m)* mut )? self
) {}
)
}
struct Foo;
impl Foo {
foo!( pub fn bar(&mut self) );
foo!( pub fn baz(&self) );
}
fn main() {
(&mut Foo).bar();
(&mut Foo).baz();
// (&Foo).bar(); //~ERROR cannot borrow
(&Foo).baz();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With