std::bad_variant_access
定义于头文件 <variant>
。
C++17
class bad_variant_access : public std::exception;
std::bad_variant_access
是在以下情况抛出的异常类型
- 调用
std::get(std::variant)
时,索引或类型与当前活跃的替代项不匹配 - 调用 std::visit 访问 valueless_by_exception 的变体时
成员函数
公开 | (构造函数) | 构造一个新的 bad_variant_access 对象 (公共成员函数) |
公开 | operator= | 替换 bad_variant_access 对象 (公共成员函数) |
公开 | what | 返回解释性字符串 (公共成员函数) |
std::bad_variant_access::bad_variant_access
bad_variant_access() noexcept; // 1) (since C++17)
bad_variant_access( const bad_variant_access& other ) noexcept; // 2) (since C++17)
构造一个新的 bad_variant_access
对象,带有一个实现定义的以 null 结尾的字节字符串,该字符串可通过 what() 访问。
-
- 默认构造函数。
-
- 复制构造函数。如果
*this
和 other 都具有动态类型std::bad_variant_access
,则std::strcmp(what(), other.what()) == 0
。
- 复制构造函数。如果
参数
other
- 要复制的另一个异常对象
std::bad_variant_access::operator=
bad_variant_access& operator=( const bad_variant_access& other ) noexcept; // (since C++17)
用 other 的内容赋值。如果 *this
和 other 都具有动态类型 std::bad_variant_access
,则赋值后 std::strcmp(what(), other.what()) == 0
。
参数
other
- 要赋值的另一个异常对象
返回值
*this
std::bad_variant_access::what
virtual const char* what() const noexcept; // (since C++17)
返回解释性字符串。
参数
(无)
返回值
指向一个以 null 结尾的字符串的指针,其中包含解释性信息。该字符串适合转换为 std::wstring
并显示。保证该指针在获取它的异常对象被销毁之前,或在调用异常对象上的非 const 成员函数(例如,复制赋值运算符)之前有效。
备注
允许但并非强制要求实现重写 what()。
继承自 std::exception
成员函数
公开 | (析构函数) [virtual] | 销毁异常对象 (std::exception 的虚公共成员函数) |
公开 | what [virtual] | 返回解释性字符串 (std::exception 的虚公共成员函数) |
示例
#include <variant>
#include <iostream>
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