gpt4 book ai didi

c++ - 是否可以传递对 consteval 函数的引用并将其用作附加返回值?

转载 作者:行者123 更新时间:2023-12-02 18:18:02 28 4
gpt4 key购买 nike

有时函数的结果不能用单个返回值来表示。例如:与两条线相交的函数。人们可能希望函数返回实际的交点以及它们之间的关系(即平行、相同、相交或倾斜)。

让我们假设这个例子,其中交点由某种类表示,线的位置关系由一个整数表示,该整数为 4 种可能性中的每一种保存指定的值:

int IntersectLines(Line l1, Line l2, Point& point);

Point point{};
int result = IntersectLines(l1, l2, point);

这就是我今天实现它的方式,但现在我想知道是否可以有一个类似的实现,但具有 consteval 函数。 LinePoint 具有 constexpr 构造函数,所有内容和计算本身也可以在编译时进行评估。唯一的问题是我想不出有两种返回值的方法。我已经想到了 std::pair 但更喜欢传递引用的解决方案。如果这样的解决方案不存在,我将不得不退回到 std::pair

通过引用传递point(Point&point)是行不通的,因为“表达式的计算结果不是常量”,但是通过 const 引用 (const Point& point) 也不起作用,因为我无法将结果分配给 point。有办法让它工作吗?

最佳答案

您可以返回 std::pair<Point, Relationship> .

示例:

consteval std::pair<Point, Relationship> IntersectLines(const Line& l1, const Line& l2) 
{
// replace with the real calc below, this is just for show:
const Point pnt{l1.p1.x + l2.p1.x, l1.p1.y + l2.p1.y};
const Relationship rel = Relationship::parallel;
return {pnt, rel};
}

并这样调用它:

int main() {
constexpr Line l1({1,2}, {3,4}), l2({5,6}, {7,8});
constexpr auto pr = IntersectLines(l1, l2);
auto&[pnt, rel] = pr;

return pnt.x + pnt.y; // 14
}

通过优化,最终的程序集可能会变成这样

main:
mov eax, 14
ret

Demo

关于c++ - 是否可以传递对 consteval 函数的引用并将其用作附加返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71276592/

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