How to declare data members that are objects of any type in a class

前端 未结 5 1786
夕颜
夕颜 2020-12-29 09:31

In this piece I\'m trying to declare in Class B a list that can hold objects of Class A of any type, such as A, A, A. I intend to add A

5条回答
  •  北海茫月
    2020-12-29 09:58

    Depending on what you're doing, type erasure might be an option. On the Tension Between Object-Oriented and Generic Programming in C++ is my favorite write-up on the subject.

    In a nutshell, you convert the static dispatch enabled by the templates into dynamic dispatch through a custom inheritance tree you setup on the fly. Instead of storing A, you create a new type that has the common interface you desire, and using some template/inhertiance voodoo this new type stores an A without actually exposing the T. So A and A and A > > > and some_type_that_looks_like_A_but_really_isnt all reduce down to a single type.

    But you have to have a common interface, independant of that parameter. If you can't, things get more difficult.

    Boost.Any is a good example, as is std::shared_ptr [which uses type erasure to remember how to delete the pointer passed to it even in the face of non-polymorphic inheritance].

提交回复
热议问题