名稱空間
變體
操作

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

來自 cppreference.com
< cpp‎ | 工具庫‎ | 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 << "value set to " << opt.value() << '\n';
    else
        std::cout << "value not set\n";
 
    opt.reset();
    if (opt.has_value())
        std::cout << "value still set to " << opt.value() << '\n';
    else
        std::cout << "value no longer set\n";
}

輸出

false
value set to 43
value no longer set