jeudi 28 janvier 2016

Defining operators using lambda functions

Consider this example:

struct A {
    int val;
    A(int val) : val(val){};

    A operator+(const A& a1) {
        return (+[](const A& a1, const A& a2) -> A {
            return A(a1.val + a2.val);
        })(*this, a1);
    };
};

int main(int argc, char* argv[]) {
    A a(14);
    A b(12);
    auto c = a + b;

    return 0;
}

I have two questions:

  1. Will the compiler optimize-out the use of lambda in this case (which is just wrapper into the operator+ or will there be any overhead?
  2. Is there any simpler syntax for writing operators using lambda functions?

Aucun commentaire:

Enregistrer un commentaire