Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class template with variable type of container

I would like to know if it's possible to create a class template with an object that has to be a container but of a kind specified by the user.

For example, now I have a class like this:

template<class T>
class Myclass {
    std::queue<T> queue;

    // SOME OTHER MEMBERS
}

But I would like to be able to make that std::queue object some other type of container when needed, like a std:stack, in order to be able to handle also containers with other kind of policies other than FIFO.

Is it possible? Or are there any other solutions that don't involve me creating another class exactly like this but with a stack instead of a queue?

like image 728
jackscorrow Avatar asked Dec 09 '25 10:12

jackscorrow


1 Answers

Sure you can. This is called a container adapter. std::queue itself is a container adapter and looks like

template<class T, class Container = std::deque<T>> 
class queue
{
    //...
};

Doing that though requires you to use something like

std::queue<int, std::vector<int>> foo;

If you want to change the container. If you do not want to have to specify the template type of the container then you can use a template template like

template<class T, template<typename...> class Container = std::queue> 
class Myclass
{
    Container<T> cont;
};

and you can use it like

Myclass<int, std::set> foo;

To change it to use a std::set instead of the default std::queue.

like image 152
NathanOliver Avatar answered Dec 10 '25 23:12

NathanOliver