命名空间
变体
操作

std::bad_any_cast

来自 cppreference.cn
< cpp‎ | utility‎ | any
 
 
 
 
定义于头文件 <any>
class bad_any_cast : public std::bad_cast;
(自 C++17 起)

定义了当 std::any_cast 的返回值形式在失败时抛出的对象类型。

内容

[edit] 成员函数

(构造函数)
构造一个新的 bad_any_cast 对象
(公共成员函数)
operator=
替换 bad_any_cast 对象
(公共成员函数)
what
返回解释性字符串
(公共成员函数)

std::bad_any_cast::bad_any_cast

bad_any_cast() noexcept;
(1) (自 C++17 起)
bad_any_cast( const bad_any_cast& other ) noexcept;
(2) (自 C++17 起)

构造一个新的 bad_any_cast 对象,该对象带有一个实现定义的空终止字节字符串,可以通过 what() 访问。

1) 默认构造函数。
2) 复制构造函数。如果 *thisother 都具有动态类型 std::bad_any_cast,则 std::strcmp(what(), other.what()) == 0

参数

other - 要复制的另一个异常对象

std::bad_any_cast::operator=

bad_any_cast& operator=( const bad_any_cast& other ) noexcept;
(自 C++17 起)

将内容赋值为 other 的内容。如果 *thisother 都具有动态类型 std::bad_any_cast,则赋值后 std::strcmp(what(), other.what()) == 0

参数

other - 要赋值的另一个异常对象

返回值

*this

std::bad_any_cast::what

virtual const char* what() const noexcept;
(自 C++17 起)

返回解释性字符串。

返回值

指向实现定义的空终止字符串的指针,其中包含解释性信息。该字符串适合转换为 std::wstring 并显示。指针保证有效,至少在从中获取它的异常对象被销毁之前,或者在异常对象上调用非 const 成员函数(例如,复制赋值运算符)之前。

返回的字符串在常量求值期间使用普通的字面量编码进行编码。

(自 C++26 起)

注释

允许但不是必须实现重写 what()

继承自 std::bad_cast

继承自 std::exception

成员函数

[虚函数]
销毁异常对象
(std::exception 的虚公共成员函数) [edit]
[虚函数]
返回解释性字符串
(std::exception 的虚公共成员函数) [edit]

[edit] 示例

#include <any>
#include <cassert>
#include <print>
 
int main()
{
    auto x = std::any(42);
    assert(std::any_cast<int>(x) == 42); // OK
 
    try
    {
        [[maybe_unused]] auto s = std::any_cast<std::string>(x); // throws
    }
    catch (const std::bad_any_cast& ex)
    {
        std::println("{}", ex.what());
    }
}

可能的输出

bad any_cast