Search code examples
c++boostboost-mplboost-variant

Get boost::variant's type index with boost::mpl


boost::variant has member types which is some kind of boost::mpl structure. Is there a way to get an index of type in that structure at compile time, so late in in runtime i could do

if(myVariantInstance.which() == typeIndex)
{
   /*...*/
}

Instead of

if(myVariantInstance.type() == typeid(ConcreteType))
{
  /*...*/
}

Solution

  • It's a bit convoluted, and there might be a better way, but you could use boost::mpl::copy. Here's something that ought to work, based off of the example from your comment:

    #include <boost/variant.hpp>
    #include <boost/mpl/copy.hpp>
    #include <boost/mpl/find.hpp>
    #include <boost/mpl/vector.hpp>
    
    typedef boost::mpl::vector<int, long, char> MyMplVector;
    typedef boost::mpl::find<MyMplVector, long>::type MyMplVectorIter;
    static_assert(MyMplVectorIter::pos::value == 1, "Error");
    
    typedef boost::variant<int, long, char> MyVariant;
    typedef boost::mpl::vector<> EmptyVector;
    typedef boost::mpl::copy<
      MyVariant::types,
      boost::mpl::back_inserter<EmptyVector>>::type ConcatType;
    
    typedef boost::mpl::find<ConcatType, long>::type MyVariantTypesIter;
    static_assert(MyVariantTypesIter::pos::value == 1, "Error");