Lambda运算符重载表达式 [英] Lambda expression for operator overloading

查看:132
本文介绍了Lambda运算符重载表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以为重载运算符编写lambda表达式?

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需要==运算符

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

可以将

==运算符定义为bool operator==(const X& lhs, const X& rhs){...},但这需要添加一个单独的函数,而我的比较仅在特定函数内有效.

== 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){...}将解决该问题.我想知道我是否可以将此lambda编写为运算符.

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

推荐答案

是否可以为重载运算符编写lambda表达式?

Is it possible to write lambda expression for overloading operators?

否.

运算符重载函数必须是函数或函数模板.它们可以是成员函数,成员函数模板,非成员函数或非成员函数模板.但是,它们不能是lambda表达式.

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.

来自 C ++ 11 Standard/13.5重载的运算符,第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.

这篇关于Lambda运算符重载表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆