boost::any 如何检查 null/undefined 值
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 is not defined" << std::endl;
}
如果没有值,boost::any::empty
将 return true
。
Demo
#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
,如果没有值,它将 return typeid(void)
:
Demo 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 对象,我想检查它的类型。
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 is not defined" << std::endl;
}
boost::any::empty
将 return true
。
Demo
#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
,如果没有值,它将 return typeid(void)
:
Demo 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