Vector that can have 3 different data types C++

后端 未结 4 1375
你的背包
你的背包 2020-11-29 10:10

I\'m trying to make a vector in C++ that can store 3 different data types. I do not want to use the boost library. Something like:

vector

        
4条回答
  •  猫巷女王i
    2020-11-29 10:50

    I'm trying to make a vector in C++ that can store 3 different data types.

    The answer here really depends on the particular use case:

    1. If the objects are somehow connected and similar in some fashion - create a base class and derive all the classes from it, then make the vector store unique_ptrs to the parent class (see ApproachingDarknessFish s answer for details),

    2. If the objects are all of fundamental (so built-in) types - use an union that groups the types and define a vector,

    3. If the objects are of unknown type, but you're sure they share a similiar interface, create a base class, and derive a templated child class from it (template class container: public parent{};), and create a vector> like in the first case,

    4. If the objects are of types that for some reason cannot be connected (so for example the vector stores int, std::string, and yourType), connect them via an union, like in 2. Or - even better...

    ...if you have time and want to learn something - look how boost::any is implemented and try implementing it yourself, if you really don't want to use the library itself. It's not as hard as it may seem.

提交回复
热议问题