如何从 Poco::Any 中获取整数

How to get integer out of Poco::Any

我将 Poco::Any 与各种整数类型一起使用,例如:

Poco::Any x = 15;
Poco::Any y = (size_t)15;
Poco::Any z = 15L;

稍后我想使用整数值:

void func(Poco::Any &a)
{

如何从中提取任何整数?一种方法是:

long n;
if ( auto *p = Poco::AnyCast<int>(&a) )
    n = *p;
else if ( auto *p = Poco::AnyCast<long>(&a) )
    n = *p;

并为每个整数类型重复。但这很丑陋。有没有更好的方法?

我试过:

Poco::Dynamic::Var var(a);
auto n = var.convert<int>(var);

但是这会抛出一个来自 VarHolder.h:

的异常
virtual void convert(Int32& val) const;
    /// Throws BadCastException. Must be overriden in a type
    /// specialization in order to suport the conversion.

您需要使用 AnyCastRefAnyCast - 虽然您可以在 Any 周围创建自己的包装器 class,并使用一种实现的新方法 return 基础对象类型,如果你不喜欢使用 typedef 或以上。

Poco::Any(它是 boost:any 的一个端口)本质上是一条关于类型的“单向道路”——你可以把任何东西放进去,但是,当你想得到出来的值,你得知道里面到底是什么;从这个意义上说,any 比 C++ 语言本身更严格。

DynamicAny (a.k.a. Poco::Dynamic::Var) 建立在any 基础上,在数据检索端“软化”它;它的引入正是为了减轻这种限制。

请参阅 DynamicAny, Part I 以获得深入的解释:

Although it provides a mechanism for dynamic type discovery (Listing 2.), boost::any does not itself get involved into such activity, nor is it willing to cooperate in implicit conversions between values of different types.

因此,如果您想坚持使用 Poco::Any,您将不得不发现其中的内容:

void func(Poco::Any &a)
{
  long n;
  if (a.type() == typeid(int))
    n = Poco::AnyCast<int>(a);
  else if (a.type() == typeid(long))
    n = Poco::AnyCast<long>(a);
  // ...
}