std::optional<T>::operator bool, std::optional<T>::has_value

来自cppreference.com
< cpp‎ | utility‎ | optional
 
 
 
 
constexpr explicit operator bool() const noexcept;
(C++17 起)
constexpr bool has_value() const noexcept;
(C++17 起)

检查 *this 是否含值。

[编辑] 参数

(无)

[编辑] 返回值

*this 含值则为 true,若 *this 不含值则为 false

[编辑] 示例

#include <optional>
#include <iostream>
 
int main()
{
    std::cout << std::boolalpha;
 
    std::optional<int> opt;
    std::cout << opt.has_value() << '\n';
 
    opt = 43;
    if (opt)
        std::cout << "设置值为 " << opt.value() << '\n';
    else
        std::cout << "未设置值\n";
 
    opt.reset();
    if (opt.has_value())
        std::cout << "值仍被设为 " << opt.value() << '\n';
    else
        std::cout << "不再设置值\n";
}

输出:

false
设置值为 43
不再设置值