What is the typical usage of boost any library?

前端 未结 5 1176
暗喜
暗喜 2020-12-30 00:44

What are the advantages of using boost.any library ? Could you please give me some real life examples ? Why the same functionality couldn\'t be achieved by having some gener

相关标签:
5条回答
  • 2020-12-30 01:13

    We use boost.any as the carrier type for a type-safe tagged variadic container. Here's what that means:

    We have a "raft" object, which travels through a set of filters. When a filter wants to add data to the raft, it can do something like this:

    raft.addTaggedData<ETag1>(3.0);
    raft.addTaggedData<ETag2>("a string")`;
    std::string str = raft.getTaggedData<ETag2>();
    int a = raft.getTaggedData<ETag1>(); // <-- Compile error
    

    Where ETag1 and ETag2 are members of an enum, and we use a traits template to map tags to types.

    The raft class is using a list of pair<ETagType, boost::any> as a backing store. Boost.any saved us the pain of managing raw buffers for various types.

    0 讨论(0)
  • 2020-12-30 01:15

    Why the same functionality couldn't be achieved by having some generic type in the root of object's hierarchy and creating containers with that base type ?

    That calls an object hierarchy -- a construct you are injecting in artificially in to the design for solving a peripheral problem. Further, such a construct is easy to get wrong and a wrong implementation can wreak havoc. Boost.Any is a community reviewed safe, well-tested alternative.

    Could you please give me some real life examples ?

    TinyJSON uses boost.Any.

    What are the advantages of using boost.any library ?

    I refer the introductory documentation.

    0 讨论(0)
  • 2020-12-30 01:18

    boost::any will happily store ints and floats, types that clearly have no base classes. A real-life example where you can use it is a virtual machine for a high-level interpreted language. Your "function" objects will need an array of arguments. This can easily be implemented with a std::list<boost::any> behind the scenes.

    0 讨论(0)
  • 2020-12-30 01:31

    I consider that Boost.Variant should always be preferred as it's non-intrusive and still calls for very structured programming.

    But i guess the main idea behind boost.any is to provide the equivalent of java and c# object types. It's a way of saying "yes we can" ! :-)

    0 讨论(0)
  • 2020-12-30 01:32

    We've used it in a property map, (std::map<std::string, boost::any>), to store a lot of things dynamically in a simple, flat dataspace.

    Mostly we either stored smart-ptr-to-scriptable-objects or strings, but some entries where other types (floats, vec3f, matrices, and other non-standard objects).

    It works pretty well for adding more dynamic capabilities to c++, or wherever you want some type-erasure to just add any type of data to an object.

    0 讨论(0)
提交回复
热议问题