5

Is it possible to write lambda expression for overloading operators?

For example, I have the following structure:

struct X{
    int value;
    //(I can't modify this structure)
};

X needs == operator

int main()
{
    X a = { 123 };
    X b = { 123 };
    //[define equality operator for X inside main function]
    //if(a == b) {}
    return 0;
}

== operator can be defined as bool operator==(const X& lhs, const X& rhs){...}, but this requires adding a separate function, and my comparison is valid only within a specific function.

auto compare = [](const X& lhs, const X& rhs){...} will solve the problem. I was wondering if I can write this lambda as an operator.

2
  • 2
    I don't understand the problem in using a non-member operator function. Can you elaborate? Commented Apr 24, 2018 at 5:57
  • 2
    A lambda is an object. An object cannot have a name like operator==. Only a function can. Commented Apr 24, 2018 at 6:02

1 Answer 1

5

Is it possible to write lambda expression for overloading operators?

No.

Operator overload functions must be functions or function templates. They can be member functions, member function templates, non-member functions, or non-member function templates. However, they cannot be lambda expressions.

From the C++11 Standard/13.5 Overloaded operators, para 6:

An operator function shall either be a non-static member function or be a non-member function and have at least one parameter whose type is a class, a reference to a class, an enumeration, or a reference to an enumeration.

Sign up to request clarification or add additional context in comments.

2 Comments

Not all operators can be non-member functions, e.g. operator=.
@HenriMenke, True. That is an additional constraint.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.