简体   繁体   English

如何支持从 Variant 类型的隐式转换,例如从 int 到 unsigned long?

[英]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.我试图让我的Variant类型,一个围绕 c++17 的std::variant的包装器,在适当的地方隐式转换类型。 For instance, a char to std::string , or int to unsigned long .例如,将char转换为std::string ,或将int转换为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?如何修改我的Variant以支持隐式类型转换?

Edit编辑

As per the comments, I also need to account for incompatible pairs as well as compatible ones, eg the following would fail.根据评论,我还需要考虑不兼容的对以及兼容的对,例如以下将失败。

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

Something along these lines:这些方面的东西:

template <typename T>
struct Visitor {
  template <typename U>
  std::enable_if_t<std::is_convertible_v<U, T>, T> operator() (U&& val) {
      return val;
  }

  template <typename U>
  std::enable_if_t<!std::is_convertible_v<U, T>, T> operator() (U&& val) {
      throw std::bad_variant_access{};
  }
};

template<class VariantType>
VariantType get() const {
    return std::visit(Visitor<VariantType>{}, static_cast<const variant_t&>(*this));
}

Demo演示

For an operator T () solution based (but with the std::variant as a member, not inherited)对于基于operator T ()解决方案(但以std::variant作为成员,不继承)

  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
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何防止从int到unsigned int的隐式转换? - How to prevent implicit conversion from int to unsigned int? 如何控制从 long 到 int 的隐式转换? - How to control implicit conversion from long to int? 没有从long unsigned int转换为long unsigned int& - No conversion from long unsigned int to long unsigned int& 如何从模板中获取容器的类型(例如 int、double、...)? C++ - How to get the type of a container (e.g. int, double,…) from a template? C++ 在C ++中从无符号long long转换为unsigned int - Conversion from unsigned long long to unsigned int in C++ 省略数据类型(例如“ unsigned”而不是“ unsigned int”) - Omitting the datatype (e.g. “unsigned” instead of “unsigned int”) 错误:从&#39;int(*)()&#39;到&#39;long unsigned int&#39;的无效转换 - error: invalid conversion from 'int (*)()' to 'long unsigned int' C++ 容器类型面临从 map 转换等问题<long unsigned int, ..>到非标量类型 map<short unsigned int, ..></short></long> - C++ container types facing an issue like conversion from map<long unsigned int, ..> to non scalar type map<short unsigned int, ..> 从int隐式转换为类类型 - Implicit conversion from int to a class type 错误:隐式转换改变了符号:&#39;int&#39; 到 &#39;unsigned long&#39; - error: implicit conversion changes signedness: 'int' to 'unsigned long'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM