std::bad_variant_access
来自 cppreference.cn
定义于头文件 <variant> |
||
class bad_variant_access : public std::exception |
(C++17 起) | |
std::bad_variant_access
是在以下情况抛出的异常类型:
- std::get(std::variant) 在调用的索引或类型与当前活跃备选项不匹配时被调用。
-
std::visit
在访问一个valueless_by_exception
的变体时被调用。
|
(C++26 起) |
目录 |
[edit] 成员函数
(构造函数) |
构造新的 bad_variant_access 对象(公开成员函数) |
operator= |
替换 bad_variant_access 对象(公开成员函数) |
what |
返回解释字符串 (公开成员函数) |
std::bad_variant_access::bad_variant_access
bad_variant_access() noexcept; |
(1) | (C++17 起) |
bad_variant_access( const bad_variant_access& other ) noexcept; |
(2) | (C++17 起) |
构造一个新的 bad_variant_access
对象,其包含一个实现定义的以 null 结尾的字节字符串,该字符串可通过 what() 访问。
1) 默认构造函数。
2) 复制构造函数。如果 *this 和 other 都具有动态类型
std::bad_variant_access
,则 std::strcmp(what(), other.what()) == 0。参数
其他 | - | 要拷贝的另一个异常对象 |
std::bad_variant_access::operator=
bad_variant_access& operator=( const bad_variant_access& other ) noexcept; |
(C++17 起) | |
将内容赋为 other 的内容。如果 *this 和 other 都具有动态类型 std::bad_variant_access
,则赋值后 std::strcmp(what(), other.what()) == 0。
参数
其他 | - | 用于赋值的另一个异常对象 |
返回值
*this
std::bad_variant_access::what
virtual const char* what() const noexcept; |
(C++17 起) | |
返回解释字符串。
返回值
指向一个实现定义的以 null 结尾的字符串,其中包含解释性信息。该字符串适合转换为 std::wstring 并显示。保证该指针至少在获取它的异常对象被销毁之前或在对异常对象调用非 const 成员函数(例如复制赋值运算符)之前有效。
在常量求值期间,返回的字符串使用普通字面量编码进行编码。 |
(C++26 起) |
注意
允许但不要求实现重写 what()
。
继承自 std::exception
成员函数
[virtual] |
销毁异常对象 ( std::exception 的虚公共成员函数) |
[virtual] |
返回解释字符串 ( std::exception 的虚公共成员函数) |
[edit] 示例
运行此代码
#include <iostream> #include <variant> int main() { std::variant<int, float> v; v = 12; try { std::get<float>(v); } catch (const std::bad_variant_access& e) { std::cout << e.what() << '\n'; } }
可能的输出
bad_variant_access
[edit] 参阅
(C++17) |
根据索引或类型(如果类型唯一)读取变体的值,出错时抛出异常 (函数模板) |
(C++17) |
用一个或多个 variant 所持有的参数调用所提供的函数对象(函数模板) |
(C++26) |
使用 variant 持有的参数调用提供的函数对象(公共成员函数) |