gpt4 book ai didi

c++ - 有没有一种通用的方法可以从所有类属性中创建一个元组?

转载 作者:行者123 更新时间:2023-12-03 06:54:21 26 4
gpt4 key购买 nike

我有很多类使用 std::tie 从所有类属性中创建一个元组并使用它来实现 == 运算符。它们看起来像这样:

class S
{
int number;
std::string text;
// and many other attributes...

auto tied() const noexcept { return std::tie(/* list all attributes here */); }

bool operator==(const S &o) const noexcept
{
return tied() == o.tied();
}
};

这些类具有相似的方法,但属性却截然不同,所以我想创建一个它们都继承自的基类,我想在基类中包含这一点比较。

但是,由于我无法定义返回 autovirtual 方法,因此我正在努力编写一个抽象的泛型 tied()应该从所有派生类的属性中创建一个元组的方法,无论它们有多少或它们是什么类型。

这可行吗?

注意:所有属性都是普通类型或std::string

最佳答案

Is there a generic way to make a tuple out of all class attributes?

无法生成成员列表。这是一种语言特性,需要比 C++ 更多的反射能力。充其量您可以有一个同时生成成员声明和生成元组的函数的宏。有关该想法的实现,请参阅 Boost Fusion。

当然,元编程不局限于C预处理器。如果您不介意使构建过程复杂化,则可以使用任何语言来生成 C++ 源代码。

I'm struggling to write an abstract generic tied()

无法编写为派生实例返回不同元组的虚拟成员函数。

Is this feasible?

没有。

and use it to implement the == operator.

自 C++20 起,您可以使用默认的 <=>生成所有比较运算符。在此之前,您需要样板文件。

关于c++ - 有没有一种通用的方法可以从所有类属性中创建一个元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64730288/

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