Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
543 views
in Technique[技术] by (71.8m points)

c++17 - 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. 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? (I don't want to use boost).

My code so far https://github.com/t348575/msgpack


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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. Check the runtime type info of the binary blob and throw a exception if the type does not match.

Solution 2: User knows the set of types that are possible, std::variant approach: Make use of the visitor pattern. 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. You need to make something like std::any which is in its essence a glorified void*.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...