Kofi
Kofi

Reputation: 645

Is there a way to pass a function as a parameter of a macro?

I'm trying to write a function similar to g_signal_connect_swapped in gtk+.

macro_rules! connect_clicked_swap {
    ($widget: tt,$other_widget: expr,$function: ident) => {
        $widget.connect_clicked(|widget| $function($other_widget))
    };
}

ident doesn't work here since I'd like to pass full path to the function.eg. gtk::ApplicationWindow::close. so I can do something like connect_clicked_swap!(button, &window, gtk::ApplicationWindow::close)

Upvotes: 1

Views: 960

Answers (1)

Peter Hall
Peter Hall

Reputation: 58875

You can use path instead of ident in order to specify a path. But the most flexible would be to use expr, which would accept paths but also expressions that return functions, including closures.

macro_rules! connect_clicked_swap {
    ($widget: tt, $other_widget: expr, $function: expr) => {
        $widget.connect_clicked(|widget| $function($other_widget))
    };
}
connect_clicked_swap!(widget1, widget2, path::to::function);
connect_clicked_swap!(widget1, widget2, |widget| println!("widget = {}", widget);

Upvotes: 3

Related Questions