Search code examples
c++type-conversionc++17variant

How to support implicit conversion from a Variant type, e.g. from int to unsigned long?


I'm trying to have my Variant type, a wrapper around c++17's std::variant, implicitly convert between types where appropriate. For instance, a char to std::string, or int to unsigned long. Here's my code:

#include <variant>

using variant_t = std::variant<
        std::monostate,
        std::string, bool, std::int32_t,
        std::uint32_t, std::int64_t, std::uint64_t,
        float, double, char, unsigned char,
        std::vector<double>>;

class Variant : public variant_t {
public:

    using variant::variant;

    enum TypeId {
        EMPTY = 0, // std::monostate. Empty is default when variant instantiated with nothing
        STRING = 1,
        BOOL = 2,
        INT32 = 3,
        UINT32 = 4,
        INT64 = 5,
        UINT64 = 6,
        FLOAT = 7,
        DOUBLE = 8,
        CHAR = 9,
        UCHAR = 10,
        DOUBLEVECTOR = 11
    };

    TypeId type() const {
        return (Variant::TypeId) index();
    }

    template<class VariantType>
    VariantType get() const {
        return std::get<VariantType>(*this);
    }
};

What I want to be able to do is this:

TEST(VariantTests, HowToConvertIntToULongWithoutManualCast) {
    Variant v(11);
    ASSERT_EQ(v.type(), Variant::TypeId::INT32); // (pass, v is an int)
    unsigned long toUnsignedLong = v; // error
    long toLong = v; // error
    // and any other conversions from int that make sense
}

How can I modify my Variant to support implicit type conversion?

Edit

As per the comments, I also need to account for incompatible pairs as well as compatible ones, e.g. the following would fail.

Variant v(12); // variant containing an int
std::string x = v; // should error, int to string incompatible

Solution

  • For an operator T () solution based (but with the std::variant as a member, not inherited)

      template <typename T>
      operator T () const 
       {
         return std::visit(
            [](auto const & val)
            { if constexpr ( std::is_convertible_v<decltype(val), T> )
                 return T(val);
               else
                { throw std::bad_variant_access{}; return T{}; } }, var); 
       }
    

    The following is a full compiling example

    #include <vector>
    #include <string>
    #include <variant>
    #include <cstdint>
    #include <type_traits>
    
    using variant_t = std::variant<
            std::monostate,
            std::string, bool, std::int32_t,
            std::uint32_t, std::int64_t, std::uint64_t,
            float, double, char, unsigned char,
            std::vector<double>>;
    
    class Variant
     {
    
       public:
          variant_t  var_;
    
        explicit Variant (variant_t var)
        : var_(std::move(var)){}
    
          enum TypeId
           {
             EMPTY = 0,
             STRING = 1,
             BOOL = 2,
             INT32 = 3,
             UINT32 = 4,
             INT64 = 5,
             UINT64 = 6,
             FLOAT = 7,
             DOUBLE = 8,
             CHAR = 9,
             UCHAR = 10,
             DOUBLEVECTOR = 11
           };
    
          TypeId type () const
           { return (Variant::TypeId) var_.index(); }
    
          template <typename VariantType>
          VariantType get () const
           { return std::get<VariantType>(var_); }
    
          template <typename T>
          operator T () const 
           {
             return std::visit(
                [](auto const & val)
                { if constexpr ( std::is_convertible_v<decltype(val), T> )
                     return T(val);
                   else
                    { throw std::bad_variant_access{}; return T{}; } }, var_); 
           }
     };
    
    int main()
     {
       Variant  v{12};
    
       long l = v;  // compile and works run-time
    
       std::string s = v; // compile and throw run-time
     }