我有一个要反序列化的序列化对象队列。 我按照序列化对象的相同顺序反序列化对象。 对象可以是多种类型,包括字符串、结构和可用的 vector 。 问题是我正在寻找一种弹出反序列化元素的主流方法。 我不高兴不得不处理:
int ex1 = deserializer.pop<int>();
box_t ex2 = deserializer.pop<box_t>();
std::string ex2 = deserializer.popString();
std::vector<float> ex3 = deserializer.popVector<float>();
我愿意做。
int ex1 = deserializer.pop<int>();
box_t ex2 = deserializer.pop<box_t>();
std::string ex3 = deserializer.pop<std::string>();
std::vector<float> ex4 = deserializer.pop<std::vector<float>>();
这是我目前所拥有的:
template<typename Test, template<typename...> class Ref>
struct is_specialization : std::false_type {};
template<template<typename...> class Ref, typename... Args>
struct is_specialization<Ref<Args...>, Ref> : std::true_type {};
template<typename data_t>
data_t pop()
{
if (is_specialization<data_t, std::vector>::value) {
std::vector<issue1> data = deserialize_vector();
return data; // issue2
} else if ((is_specialization<data_t, std::string>::value)) {
std::string data = deserialize_string();
return data; // issue2
} else {
return deserialize<data_t>();
}
}
issue1:如何判断vector的数据类型? 问题 2:编译器不会返回显式定义的类型。 甚至可以在一个函数中实现吗?
感谢您的宝贵时间。
最佳答案
这看起来是一个很好的标签分发用例。使用辅助函数根据提供的类型进行重载,并为这些类型调用专门的 deserialize
函数。辅助 type_t
标签类型可用于保存类型,它还有助于简化界面。
namespace impl {
template<class T> struct type_t { using type=T; };
template<class T>
T pop( type_t<T> ) {
return deserialize<T>();
}
template<class T>
std::vector<T> pop( type_t<std::vector<T>> ) {
return deserialize_vector();
}
std::string pop( type_t<std::string> ) {
return deserialize_string();
}
}
然后在你的外层 pop
中:
template<typename data_t>
data_t pop() {
return impl::pop( impl::type_t<data_t>{} );
}
关于c++ - 关于反序列化器弹出函数的模板化特化的歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56696199/