Why is `boost::any` better than `void*`?

前端 未结 4 545
青春惊慌失措
青春惊慌失措 2021-02-01 07:50

What inherent advantages do boost::any and boost::any_cast offer over using void* and dynamic_cast?

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-01 08:25

    The advantage is that boost::any is way more type-safe than void*.

    E.g.

    int i = 5;
    void* p = &i;
    static_cast(p);  //Compiler doesn't complain. Undefined Behavior.
    boost::any a;
    a = i;
    boost::any_cast(a); //throws, which is good
    

    As to your comment, you cannot dynamic_cast from a void*. You can dynamic_cast only from pointers and references to class types which have at least one virtual function (aka polymorphic types)

提交回复
热议问题