首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::optional::value_or

template< class U > constexpr T value_or( U&& default_value ) const&;

(since C++17)

template< class U > constexpr T value_or( U&& default_value ) &&;

(since C++17)

返回包含的值,如果*this有一个值,否则返回default_value...

1%29相当于bool(*this)?**this :static_cast<T>(std::forward<U>(default_value))

2%29相当于bool(*this)? std::move(**this):static_cast<T>(std::forward<U>(default_value))

参数

default_value

-

the value to use in case *this is empty

类型要求

-T必须符合CopyConstrucable的要求,才能使用过载%281%29。

-T必须符合可移动建筑的要求,才能使用过载%282%29。

-U&&&必须转换为T。

返回值

当前值如果*this有价值,或default_value否则。

例外

返回值的选定构造函数引发的任何异常。T...

二次

代码语言:javascript
复制
#include <optional>
#include <iostream>
#include <cstdlib>
 
std::optional<const char*> maybe_getenv(const char* n)
{
    if(const char* x = std::getenv(n))
       return x;
    else
       return {};
}
int main()
{
     std::cout << maybe_getenv("MYPWD").value_or("(none)") << '\n';
}

二次

可能的产出:

二次

代码语言:javascript
复制
(none)

二次

另见

value

returns the contained value (public member function)

代码语言:txt
复制
 © cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券