gpt4 book ai didi

c++ - 用于运算符重载的 Lambda 表达式

转载 作者:太空狗 更新时间:2023-10-29 20:34:14 26 4
gpt4 key购买 nike

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

例如我有如下结构:

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){...},但这需要添加一个单独的函数,并且我的比较仅在特定函数内有效。

auto compare = [](const X& lhs, const X& rhs){...} 将解决问题。我想知道我是否可以将此 lambda 编写为运算符。

最佳答案

Is it possible to write lambda expression for overloading operators?

没有。

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

来自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.

关于c++ - 用于运算符重载的 Lambda 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49994213/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com