英文:
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 "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";
}
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 << std::boolalpha << (a.type() == typeid(int)) << std::endl; // true
boost::any b;
std::cout << std::boolalpha << (b.type() == typeid(void)) << std::endl; // true
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论