C ++ Any way to store different templates in one container

Is there any hack I could use for this:

template <class TYPE>
class Hello
{
     TYPE _var;
};

I would like to save

Hello<int> intHello and Hello<char*> charHello

in the same Container as Queue / List.

+3
source share
3 answers

No, because they are different and completely unrelated types.

However, you can use inheritance and smart pointers:

class HelloBase 
{
public:
    virtual ~HelloBase(); 
}

template <class TYPE>
class Hello : public HelloBase
{
    TYPE _var;
}

std::vector<boost::shared_ptr<HelloBase> > v;

shared_ptrmay be supported by your implementation either in the namespace std::tr1, or std; you will need to check.

+9
source

, - , , . , , Hello<int> Hello<char *> . , , , .

, , / Boost::any.

+5

, : ( )?

, . , :

  • Hello<T> , , (unique_ptr boost::ptr_list )
  • if there is an exact set of types, use it boost::variant, it is statically checked so that you have reasonable guarantees.
  • else you should consider moving it to a storage class that will be used boost::anyunder covers

A common base class is a common approach in this situation. If there is no reason to have polymorphism, use preferably variant, and if nothing else any.

+4
source

Source: https://habr.com/ru/post/1743995/


All Articles