小编wou*_*eto的帖子

C++:检查存储在 std::any 中的值是否为整数

有一个值存储在std::any,我想知道它是整数值(char, short, int, long,有符号和无符号)还是浮点值(float, double),或其他东西。

如果我只需要检查int值,我会这样做:

std::any a;
if (a.type() == typeid(int)) {
  // do some logic for int
}
Run Code Online (Sandbox Code Playgroud)

但是if (a.type() == typeid(int) || a.type() == typeid(signed char)...)在 C++ 中为所有整数类型做一个巨人似乎......很糟糕。

如果我可以以某种方式访问该类型,我可以使用is_arithmetic<T>from但我没有,我只有which 返回。type_traitsTstd::any#type()std::type_info

有没有办法在if条件中没有很多很多分离的情况下实现这一点?

(如果重要的话,我使用 C++20)

c++ stdany c++20

5
推荐指数
1
解决办法
123
查看次数

标签 统计

c++ ×1

c++20 ×1

stdany ×1