c++ - 结合 static_cast 和 std::any_cast

标签 c++ c++17

是否存在安全的 std::any_caststatic_cast 组合?

我正在尝试执行以下操作:

#include <any>
#include <iostream>

int main( )
{
    auto x = std::make_any< int >( 5 );
#if 0 // doesn't work
    std::cout << std::any_cast< short >( x );
#else // works, but requires knowing the initial type
    std::cout << static_cast< short >( std::any_cast< int >( x ) );
#endif
}

最佳答案

std::any 中获取值的唯一方法是 any_cast<T>哪里T有相同的 typeid作为里面的值(您可以使用 .type() 方法检查它)。

如果您需要其他语义,例如“取一个值当且仅当它可以转换为 int ”,你必须使用其他东西来进行类型删除。例如,您可以自己编写一个。

关于c++ - 结合 static_cast 和 std::any_cast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70313749/

相关文章:

c++ - g++,创建用于分发的静态库

c++ - 编译时生成应在构造函数中创建的非 constexpr 对象的数组

C++ std::filesystem::filesystem_error 异常试图读取系统卷信息等

c++ - MSVC 常量枚举类型

C++17 和十进制浮点的当前状态

C++:静态断言仿函数的参数是 const 引用

c++ - 在不违反严格的别名规则的情况下访问进程间共享内存中的对象

c++ - 当 C++ 实现向 C 代码抛出异常时会发生什么

c++ - 如何在具有抽象类多重继承的 C++ 中使用 clone()?

c++ - '<<' 标记之前的预期构造函数、析构函数或类型转换