std::variant_npos
来自 cppreference.cn
定义于头文件 <variant> |
||
inline constexpr std::size_t variant_npos = -1; |
(C++17 起) | |
这是一个特殊值,等于类型 std::size_t 所能表示的最大值,当 valueless_by_exception() 为 true 时,作为 index() 的返回值。
运行此代码
#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 所持可选类型的零基索引(public member function) | |
检查 `variant` 是否处于无效状态 (public member function) |