简体   繁体   English

返回任何/未知类型 c++

[英]Return any / unknown type c++

I am attempting to implement msgpack (a json alternative) in c++, and am creating an Iterator class to loop over my byte array, which is separated based on certain headers.我正在尝试在 c++ 中实现msgpack (json 替代方案),并正在创建一个迭代器 class 来循环遍历我的字节数组,该数组基于某些标头分隔。 So how would the iterator construct and return any type, Eg.那么迭代器将如何构造并返回任何类型,例如。 vector<int> , map<int, string> etc. Is std::any or std::variant the only way to do this? vector<int>map<int, string>std::anystd::variant是唯一的方法吗? (I don't want to use boost). (我不想使用提升)。

My code so far https://github.com/t348575/msgpack到目前为止我的代码https://github.com/t348575/msgpack

There are different approaches for what you want to do and each one has its own requirements and drawbacks.您想要做的事情有不同的方法,每种方法都有自己的要求和缺点。

Solution 1: The user knows at compiletime what the serialized data looks like Just write a template function that takes a type and try do deserialize into it.解决方案 1:用户在编译时就知道序列化数据是什么样子只需编写一个模板 function 接受一个类型并尝试对其进行反序列化。 Check the runtime type info of the binary blob and throw a exception if the type does not match.检查二进制 blob 的运行时类型信息,如果类型不匹配则抛出异常。

Solution 2: User knows the set of types that are possible, std::variant approach: Make use of the visitor pattern.解决方案 2:用户知道可能的类型集,std::variant 方法:利用访问者模式。 You can look at the interface of variant for details.您可以查看变体的界面以了解详细信息。

Solution 3: The user has no clue of what types are to come: You are pretty much out of luck here.解决方案 3:用户不知道会出现什么类型:您在这里很不走运。 You need to make something like std::any which is in its essence a glorified void*.你需要制作像 std::any 这样的东西,它本质上是一个美化的 void*。

C++ is designed to be a statically typed language. C++ 被设计为静态类型语言。 Hence what you're trying to accomplish (getting a function to return a type determined run-time) is expectedly a struggle:).因此,您要完成的工作(让 function 返回类型确定的运行时)预计是一场斗争:)。 I'd personally avoid this approach.我个人会避免这种方法。

std::variant is one solution but it is only going to result in the client probing the content of each return value in a big case statement; std::variant 是一种解决方案,但它只会导致客户端在大 case 语句中探测每个返回值的内容; or subsequently getting a callback from the visitor pattern.或随后从访问者模式中获得回调。 Neither is really the best way to get output from a parser.两者都不是从解析器获取 output 的最佳方法。

I'd have a look at good C++ JSON parsers, see how they solve serialization/deserialization, eg https://github.com/nlohmann/json我会看看好的 C++ JSON 解析器,看看它们如何解决序列化/反序列化,例如https://github.com/nlo

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM