c++typesdecltypeboost-varianttypeid

How to get currently held variant type, and define new variables of that type


I have a boost::variant of types such as:

typedef boost::variant< uint8_t, int8_t, uint16_t, int16_t,
                uint32_t, int32_t, float, double, std::string > StorageTt;

A StorageTt variable, say val, is set to one of these storage types later in my code. I'd like to retrieve the type that val currently holds to define more variables of that same type. So if val is currently a uint16_t, I want to do something like:

typedef decltype(typeid(val)) StorageTt;
StorageTt new_val = 42;  // new_val should be a uint16_t

but this yields a const type_info type. I know I can do:

switch (val.which()) {
    case 0: // uint8_t
    case 1: //...

but I'd rather avoid the long switch-statement, because I have to do this multiple times.


Solution

  • You can do something like this using a visitor functor with a call operator template:

    struct MyVisitor : public boost::static_visitor<>
    {
        template <typename StorageT>
        void operator()(const StorageT&) const
        {
            StorageT new_val = 32; // declare variable with same type
    
            doSomethingWith(new_val); // do something with it
        }
    };
    

    Apply it to the variant val like so:

    boost::apply_visitor(MyVisitor(), val);
    

    Reference:

    I'm not aware of a way to replace the functor with a C++14 generic lambda.