名前空間
変種
操作

std::experimental::optional<T>::value_or

From cppreference.com
 
 
 
 
 
template< class U >
constexpr T value_or( U&& default_value ) const&;
(Library Fundamentals TS)
template< class U >
constexpr T value_or( U&& default_value ) &&;
(Library Fundamentals TS)

値を持つ場合は格納された値を返し、それ以外の場合は default_value を返します。

1) bool(*this) ? **this : static_cast<T>(std::forward<U>(default_value)) と同等です。
2) bool(*this) ? std::move(**this) : static_cast<T>(std::forward<U>(default_value)) と同等です。

目次

[編集] パラメータ

default_value - *this が空の場合に使用される値
型要件
-
オーバーロード (1) を使用するには、TCopyConstructible の要件を満たす必要があります。
-
オーバーロード (2) を使用するには、TMoveConstructible の要件を満たす必要があります。
-
U&&T に変換可能である必要があります。

[編集] 戻り値

*this が値を持つ場合は現在の値、それ以外の場合は default_value

[編集] 例外

戻り値の型 T の選択されたコンストラクタによってスローされる例外。

[編集]

#include <cstdlib>
#include <experimental/optional>
#include <iostream>
 
std::experimental::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';
}

実行結果の例

(none)

[編集] 関連項目

保持されている値を返す
(public member function) [編集]
English 日本語 中文(简体) 中文(繁體)