c++boosttypesnullboost-any

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


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;
}

Solution

  • 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