c++c++11boostunsigned-integerboost-any

boost::any with structs and unsigned ints


There are several parts to my question. I have been researching on how/when to use boost::any. I was wondering if it is possible to assign a struct to a boost::any variable.

Example:

struct S {
   int x;
};

S s;
s.x = 5;

boost::any var = s;

It would seem to me that this is possible but it leads me to my next question. If this is a valid assignment, then how would I access the data member x? var is not a struct type since it is boost::any.

My next question is not dependent on whether the data member can be accessed or not. The question then is, what if variable a is of type uint8_t.

Example: Edit: as pointed out in the comments, the code below does support uint8_t but it is not printed. See uint8_t can't be printed with cout.

uint8_t a = 10;

boost::any b = a;

std::cout << boost::any_cast<uint8_t>(b);

I found that it is possible to use boost::any_cast but have not found that it supports unsigned types. When I tried using boost::any_cast<uint8_t>() it did not print, but did not throw an error. Is it possible to get the value of a type like uint8_t using boost? If so how?

I will continue reading more documentation of boost::any but if anyone has insight, details, or notes on these questions or the subject, please post as I would love to learn more about how this works. Thanks!


Solution

  • I was wondering if it is possible to assign a struct to a boost::any variable

    It is.

    How would I access the data member x?

    You would access with any_cast<S>(var).x. Continuing your example:

    int& the_x_member = any_cast<S>(var).x;
    std::cout << "s.x is " << the_x_member << "\n";
    

    What if variable a is of type uint8_t?

    It's perfectly possible to assign an unsigned integer type to a boost::any (or std::any, which does the same thing but with somewhat different syntax).

    When I tried using boost::any_cast<uint8_t>() it did not print, but did not throw an error.

    Wouldn't that "print" a \0 character? So it would look like nothing was printed.

    Is it possible to get the value of a type like uint8_t using Boost? If so how?

    Just like you'd expect:

    uint8_t u = 234;
    boost::any ba = u;
    std::cout << "u is " << (int) boost::any_cast<uint8_t>(ba) << '\n';
    

    This does indeed work.