【发布时间】:2019-04-16 10:26:41
【问题描述】:
当我开始利用 C++17 结构化绑定和 if 运算符 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
}
}
这对我很有用,但现在我想知道是否有某种标准等效于这个模板,这样我就不必重新发明轮子并自己定义它。似乎任意类型值加上有效性标志将是一个有用的构造,但我在标准库中找不到任何东西。我错过了什么吗?
【问题讨论】:
标签: c++ c++17 c++-standard-library