std::bad_variant_access
来自cppreference.com
                    
                                        
                    
                    
                                                            
                    |   定义于头文件  <variant>
  | 
||
|   class bad_variant_access : public std::exception  | 
(C++17 起) | |
std::bad_variant_access 是下列情形中抛出的异常类型:
- 以不匹配当前活跃可选项的下标或类型调用 std::get(std::variant)
 -  调用 std::visit 观览因异常无值 (valueless_by_exception) 的 
variant 
成员函数
|    (构造函数)  | 
  构造新的 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 对象,字符串能通过 what() 访问。
1) 默认构造函数。
2) 复制构造函数。若 
*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;  | 
(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;  | 
(C++17 起) | |
返回解释字符串。
参数
(无)
返回值
指向有解释信息的空终止字符串的指针。该字符串适合转换并显示为 std::wstring 。保证该指针至少到获得它来源的异常对象被销毁,或在该异常对象上调用非 const 成员函数(例如复制赋值运算符)为止合法。
注解
允许但不要求实现覆写 what() 。
继承自 std::exception
成员函数
|    [虚]  | 
  析构该异常对象  ( std::exception 的虚公开成员函数)  | 
|    [虚]  | 
   返回解释性字符串  ( 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
参阅
|    (C++17)  | 
  以给定索引或类型(若类型唯一)读取 variant 的值,错误时抛出异常  (函数模板)  | 
|    (C++17)  | 
  以一或多个 variant 所保有的各实参调用所提供的函数对象 (函数模板)  |