why doesn't std::any_cast support implicit conversion?

后端 未结 5 948
傲寒
傲寒 2020-12-24 12:33

Why does std::any_cast throw a std::bad_any_cast exception when an implicit conversion from the actual stored type to the requested type would be p

5条回答
  •  借酒劲吻你
    2020-12-24 13:17

    This could be implemented by trying a contingency implicit conversion, if the type id of the requested type was not the same as the type id of the stored type. But it would involve a cost and hence violate the "not pay for what you don't use" principle. Another any shortcoming, for example, is the inability to store an array.

    std::any("blabla");
    

    will work, but it will store a char const*, not an array. You could add such a feature in your own customized any, but then you'd need to store a pointer to a string literal by doing:

    any(&*"blabla");
    

    which is kind of odd. The decisions of the Standard committee are a compromise and never satisfy everyone, but you fortunately have the option of implementing your own any.

    You could also extend any to store and then invoke type-erased functors, for example, but this is also not supported by the Standard.

提交回复
热议问题