命名空间
变体 (Variants)
视图 (Views)
操作 (Actions)

std::variant_npos

来自 cppreference.cn
< cpp‎ | utility‎ | variant
 
 
 
 
定义于头文件 <variant>
inline constexpr std::size_t variant_npos = -1;
(自 C++17 起)

这是一个特殊值,等于类型 std::size_t 可表示的最大值,当 index()valueless_by_exception()true 时作为返回值使用。

#include <iostream>
#include <stdexcept>
#include <string>
#include <variant>
 
struct Demon
{
    Demon(int) {}
    Demon(const Demon&) { throw std::domain_error("copy ctor"); }
    Demon& operator= (const Demon&) = default;
};
 
int main()
{
    std::variant<int, Demon> var{42};
    std::cout
        << std::boolalpha
        << "index == npos: " << (var.index() == std::variant_npos) << '\n';
 
    try { var = Demon{666}; } catch (const std::domain_error& ex)
    {
        std::cout
            << "Exception: " << ex.what() << '\n'
            << "index == npos: " << (var.index() == std::variant_npos) << '\n'
            << "valueless: " << var.valueless_by_exception() << '\n';
    }
}

可能的输出

index == npos: false
Exception: copy ctor
index == npos: true
valueless: true

[编辑] 参见

返回 variant 所持有的候选项的从零开始的索引
(公共成员函数) [编辑]
检查 variant 是否处于无效状态
(公共成员函数) [编辑]