Class template with variable container type

I would like to know if it is possible to create a class template with an object that should be a container, but with a view 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 this object std::queue

some other type of container when needed, for example std:stack

to be able to handle also containers with other policies than FIFO.

Is it possible? Or are there any other solutions that don't assume I am creating another class this way, but with stack

instead queue

?

+3


source to share


1 answer


Sure. This is called a container adapter. std::queue

is itself a container adapter and looks like

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

      

To do this, you need to use something like

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

      

If you want to change the container. If you don't want to specify the type of container template 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, use std::set

instead of the default std::queue

.

+4


source







All Articles