impl_ops

Macro impl_op_ex_commutative

Source
macro_rules! impl_op_ex_commutative {
    ($op:tt |$lhs_i:ident : &$lhs:path, $rhs_i:ident : &$rhs:path| -> $out:path $body:block) => { ... };
    ($op:tt |$lhs_i:ident : &$lhs:path, $rhs_i:ident : $rhs:path| -> $out:path $body:block) => { ... };
    ($op:tt |$lhs_i:ident : $lhs:path, $rhs_i:ident : &$rhs:path| -> $out:path $body:block) => { ... };
    ($op:tt |$lhs_i:ident : $lhs:path, $rhs_i:ident : $rhs:path| -> $out:path $body:block) => { ... };
}
Expand description

Overloads a binary operator commutatively using the given closure as its body. Generates overloads for both owned and borrowed variants where possible.

See impl_op_commutative! for usage.

Expands borrowed inputs to both borrowed and owned variants.

impl_op_ex_commutative!(op |a: &LHS, b: &RHS| -> OUT {...});
// where LHS != RHS

gets expanded to

impl_op!(op |a: &LHS, b: &RHS| -> OUT {...});
impl_op!(op |a: &LHS, b: RHS| -> OUT {...});
impl_op!(op |a: LHS, b: &RHS| -> OUT {...});
impl_op!(op |a: LHS, b: RHS| -> OUT {...});

impl_op!(op |a: &RHS, b: &LHS| -> OUT {...});
impl_op!(op |a: &RHS, b: LHS| -> OUT {...});
impl_op!(op |a: RHS, b: &LHS| -> OUT {...});
impl_op!(op |a: RHS, b: LHS| -> OUT {...});

§Examples

#[macro_use] extern crate impl_ops;
use std::ops;

impl_op_ex_commutative!(+ |a: &DonkeyKong, b: &DiddyKong| -> i32 { a.bananas + b.bananas });
impl_op_ex_commutative!(+ |a: &DonkeyKong, b: i32| -> i32 { a.bananas + b });

fn main() {
    let total_bananas = &DonkeyKong::new(5) + &DiddyKong::new(1);
    assert_eq!(6, total_bananas);
    let total_bananas = &DonkeyKong::new(5) + DiddyKong::new(1);
    assert_eq!(6, total_bananas);
    let total_bananas = DonkeyKong::new(5) + &DiddyKong::new(1);
    assert_eq!(6, total_bananas);
    let total_bananas = DonkeyKong::new(5) + DiddyKong::new(1);
    assert_eq!(6, total_bananas);

    let total_bananas = &DiddyKong::new(1) + &DonkeyKong::new(5);
    assert_eq!(6, total_bananas);
    let total_bananas = &DiddyKong::new(1) + DonkeyKong::new(5);
    assert_eq!(6, total_bananas);
    let total_bananas = DiddyKong::new(1) + &DonkeyKong::new(5);
    assert_eq!(6, total_bananas);
    let total_bananas = DiddyKong::new(1) + DonkeyKong::new(5);
    assert_eq!(6, total_bananas);

    let total_bananas = &DonkeyKong::new(5) + 1;
    assert_eq!(6, total_bananas);
    let total_bananas = DonkeyKong::new(5) + 1;
    assert_eq!(6, total_bananas);

    let total_bananas = 1 + &DonkeyKong::new(5);
    assert_eq!(6, total_bananas);
    let total_bananas = 1 + DonkeyKong::new(5);
    assert_eq!(6, total_bananas);
}