gpt4 book ai didi

c++ - 返回带有 bool 结果标志的值的标准模板

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:18:00 26 4
gpt4 key购买 nike

当我开始利用 C++17 结构化绑定(bind)和 if operator init 语句来进行更优雅的函数结果报告和检查时,如果符合 C++ 核心指南 F21,我开始执行以下操作:

std::pair<bool, int>Foo()
{
return {true, 42}; //true means that function complete with no error and that 42 is a good value
}

void main(void)
{
if (auto [Result, Value] = Foo(); Result)
{
//Do something with the return value here
}
}

然后,当然,我认为为此类返回类型提供一个可重用的模板会很好,这样就没有人必须复制该对的 bool 部分:

template <typename T> using validated = std::pair<bool,T>;

validated<int> Foo()
{
return {true, 42};
}

void main(void)
{
if (auto [Result, Value] = Foo(); Result)
{
//Do something with the return value here
}
}

这对我来说非常有用,但现在我想知道是否有某种与此模板等效的标准,这样我就不必重新发明轮子并自己定义它。似乎任意类型值加上有效性标志将是一个有用的结构,但我在标准库中找不到任何东西。我错过了什么吗?

最佳答案

std::optional正是你要问的。它甚至在描述中:

A common use case for optional is the return value of a function that may fail. As opposed to other approaches, such as std::pair<T,bool>, optional handles expensive-to-construct objects well and is more readable, as the intent is expressed explicitly.

if从这个例子看起来会更直接一些:

#include <optional>
#include <iostream>

std::optional<int> Foo(bool fail)
{
if (!fail) return {42};
return {};
}

void process(bool fail) {
if (auto val = Foo(fail)) {
std::cout << val.value() << '\n';
} else {
std::cout << "No value!\n";
}
}

int main() {
std::optional<int> oi;
process(true);
process(false);
}

如果你真的想使用 Value明确地那么你总是可以通过成功分支上的引用来解压缩它,即 auto Value = val.value() ;

您需要注意一些注意事项。 2 从我的头顶:

  1. 表现:Why is the construction of std::optional<int> more expensive than a std::pair<int, bool>?尽管对于给定的示例 up-to-date clang with -O3 looks pretty convicing

    Note: static was added for process for brevity - to prevent generation of version for external linking.

  2. 它将返回 false如果对象是默认构造的。这可能会让一些人感到惊讶,optional 的默认构造不默认构造潜在值(value)。

编辑:在发表评论后,我决定明确声明 没有类似 pair<T,bool> 的类型别名之类的东西。 或类似的与标准库兼容的。证明某些东西不存在并不容易,但如果存在这样的类型,标准库肯定会在 insert 的声明中使用它。 ,它没有;因此,我强烈暗示它周围没有任何语义包装器。

关于c++ - 返回带有 bool 结果标志的值的标准模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53283528/

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