如何检查 boost::any 是否为 null/undefined 值

huangapple go评论66阅读模式
英文:

boost::any how to check for a null/undefined value

问题

以下是您要翻译的代码部分:

我有一个 boost::any 对象,我想要检查它的类型。

typedef boost::any Value;

Value a = 12;

if(a.type() == typeid(int)) {
    std::cout << boost::any_cast<int>(a) << std::endl;
}

这在类型已定义时很容易,但是当类型未定义时(即因为尚未设置其值)如何实现相同的结果呢?

Value b;

if(b is undefined) {
   std::cout << "b 未定义" << std::endl;
}
英文:

I have a boost::any object, and I would like to check its type.

typedef boost::any Value;

Value a = 12;

if(a.type() == typeid(int)) {
    std::cout << boost::any_cast<int>(a) << std::endl;
}

This is easy enough when the type is defined, however how would I achieve a the same result when the type is not defined (i.e. because its value has not been set yet).

Value b;

if(b is undefined) {
   std::cout << "b is not defined" << std::endl;
}

答案1

得分: 2

boost::any::empty 返回 true,如果没有值。

演示

#include "boost/any.hpp"
#include <iostream>

int main()
{
    boost::any a = 42;
    if (!a.empty())
        std::cout << "a has a value\n";
    
    boost::any b;
    if (b.empty())
        std::cout << "b does not have a value\n";
}

或者,你可以像在第一个示例中那样使用 boost::any::type,如果没有值,它将返回 typeid(void):

演示 2

boost::any a = 42;
std::cout << std::boolalpha << (a.type() == typeid(int)) << std::endl; // true

boost::any b;
std::cout << std::boolalpha << (b.type() == typeid(void)) << std::endl; // true
英文:

boost::any::empty will return true if there is no value.

Demo

#include &quot;boost/any.hpp&quot;
#include &lt;iostream&gt;

int main()
{
    boost::any a = 42;
    if (!a.empty())
        std::cout &lt;&lt; &quot;a has a value\n&quot;;
    
    boost::any b;
    if (b.empty())
        std::cout &lt;&lt; &quot;b does not have a value\n&quot;;
}

Alternatively, you can use boost::any::type like you did in the first example and, if there's no value, it will return typeid(void):

Demo 2

boost::any a = 42;
std::cout &lt;&lt; std::boolalpha &lt;&lt; (a.type() == typeid(int)) &lt;&lt; std::endl; // true

boost::any b;
std::cout &lt;&lt; std::boolalpha &lt;&lt; (b.type() == typeid(void)) &lt;&lt; std::endl; // true

huangapple
  • 本文由 发表于 2020年1月3日 22:33:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/59580366.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定