gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 03:27:46 25 4
gpt4 key购买 nike

我想拥有我的 Variant类型,C++17 的包装器 std::variant , 在适当的地方隐式转换类型。例如,charstd::string , 或 intunsigned long .这是我的代码:

#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);
}
};
我希望能够做的是:
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
}
如何修改我的 Variant支持隐式类型转换?
编辑
根据评论,我还需要考虑不兼容的对以及兼容的对,例如以下将失败。
Variant v(12); // variant containing an int
std::string x = v; // should error, int to string incompatible

最佳答案

沿着这些路线的东西:

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

关于c++ - 如何支持 Variant 类型的隐式转换,例如从 int 到 unsigned long?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67348379/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com