gpt4 book ai didi

c++ - Expected 的替代实现

转载 作者:行者123 更新时间:2023-11-28 03:06:55 25 4
gpt4 key购买 nike

最近我看了一个presentation about "Systematic Error Handling in C++"由 Andrei Alexandrescu 提供。拟议的Expected模板结构如下:

template<class T> class Expected {
union {
T ham;
std::exception_ptr spam;
};
bool gotHam;
};

使用 union 会使实现有点复杂,因为您需要按 gotHam 字段进行分支,然后然后决定如何处理 union 中的数据。 IE。 hamspam 无法在初始化列表上进行初始化。

我想知道简化版本是否会更好。

template<class T> class Expected {
union { T ham; };
std::exception_ptr spam;
};

在这种情况下,spam 可以用作发生错误时的指示器。

最佳答案

您可以在 ham 上使用指针,这样就不会调用默认构造函数,并且您不需要在您的版本中没有真正意义的 union 。

另外,我不认为你的版本改变了分支的需要,因为你仍然需要测试异常指针而不是 bool 值。

关于c++ - Expected<T> 的替代实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19448063/

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