gpt4 book ai didi

c++ - 是否可以使用 std::variant 的 std::variants

转载 作者:太空宇宙 更新时间:2023-11-04 15:55:16 28 4
gpt4 key购买 nike

我试图将两个变体组合成一个变体只是为了便于阅读。这是代码:

using VariantType_basic = std::variant<int8_t, uint8_t, int16_t, uint16_t, int32_t, uint32_t, int64_t, uint64_t, std::string>;
using VariantType_vector = std::variant<vector<int8_t>, vector<uint8_t>, vector<int16_t>, vector<uint16_t>, vector<int32_t>, vector<uint32_t>, vector<int64_t>, vector<uint64_t>, vector<std::string>>;
using VariantType_all = std::variant<VariantType_basic, VariantType_vector>;

class Container {
public:
Container(){}
template<typename T>
T get(string key, bool &found){
found = false;
T result;
auto elem = m_internal_map.find(key);
if(elem != m_internal_map.end())
std::visit(
[&](const auto& v){
// if(holds_alternative<T>(v)){

result = std::get<T>(v);
found = true;
//}
},
elem->second
);

return result;
}

template<typename T>
void put(string key, T&elem){

}
private:
map<string, VariantType_all> m_internal_map;
};

get() 方法在编译时失败 result = std::get<T>(v);当我尝试做这样的事情时:

Container cont;
bool found;
cont.get<uint16_t>("www", found);

错误消息很大,但第一条错误消息是这样的:/usr/include/c++/7/variant:762:7: error: static assertion failed: T should occur for exactly once in alternatives

我应该停止尝试使用变体的变体吗?

最佳答案

我建议“扁平化”变体而不是变体的变体:

template <typename Var1, typename Var2> struct variant_flat;

template <typename ... Ts1, typename ... Ts2>
struct variant_flat<std::variant<Ts1...>, std::variant<Ts2...>>
{
using type = std::variant<Ts1..., Ts2...>;
};

using VariantType_basic = std::variant<int8_t, uint8_t, int16_t, uint16_t, int32_t, uint32_t, int64_t, uint64_t, std::string>;
using VariantType_vector = std::variant<std::vector<int8_t>, std::vector<uint8_t>, std::vector<int16_t>, std::vector<uint16_t>, std::vector<int32_t>, std::vector<uint32_t>, std::vector<int64_t>, std::vector<uint64_t>, std::vector<std::string>>;
using VariantType_all = variant_flat<VariantType_basic, VariantType_vector>::type;

而且你的类(class)只需要处理一个变体级别:

class Container
{
public:
Container(){}

template<typename T>
T get(const std::string& key, bool &found) const {
found = false;
T result;
auto elem = m_internal_map.find(key);
if (elem != m_internal_map.end() && std::holds_alternative<T>(elem->second)){
result = std::get<T>(elem->second);
found = true;
}
return result;
}

template<typename T>
void put(const std::string& key, const T& elem) {
m_internal_map[key] = elem;
}
private:
std::map<std::string, VariantType_all> m_internal_map;
};

Demo

关于c++ - 是否可以使用 std::variant 的 std::variants,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59250481/

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