c++ template: allocator for template container

醉酒当歌 提交于 2019-12-10 11:33:36

问题


In my c++ template struct I want to use different container types which use different allocators, e.g. std::vector and thrust::device_vector.

I need to specify the allocator explicitely, otherwise I get "wrong number of template arguments (1, should be 2)":

template<typename T, template <typename, typename> class Container, typename Alloc>
struct wrap_into_container
{
    typedef Container<T, Alloc> type;
};

Since the different container classes use different allocators, I have to specify the corresponding allocator everytime I want to use this template.

How can I get the allocator depending on the Container type without having to specify it?

I thought of using a traits struct which I then specialize for each Container type, but I don't know how to implement it or if it is even useful / possible / ...

UPDATE: I cannot use C++11 unfortunately due to restrictions of the NVIDIA compiler ...


回答1:


In c++11, I favour variadics

template<typename T, template <typename...> class Container>
struct wrap_into_container
{
    typedef Container<T>::type type;
};

(I haven't checked whether C::type is actually a wellformed expression for standard container types)

To the comment:

template<typename T, template <typename...> class Container>
struct wrap_into_container
{
    typedef Container<T>::type type;
};

For C++03 you can emulate a template alias using nested typedefs, essentially making a unary type-function taking a single element type and returning a container of that type. The concept:

#include <vector>
#include <deque>
#include <set>
#include <list>

namespace container
{
    template <typename T> struct vector { typedef std::vector<T> type; };
    template <typename T> struct set    { typedef std::set   <T> type; };
    template <typename T> struct list   { typedef std::list  <T> type; };
    template <typename T> struct deque  { typedef std::deque <T> type; };
}

template<typename T, template <typename> class Container>
struct wrap_into_container
{
    typedef typename Container<T>::type type;
};

#include <string> 

int main() {

    wrap_into_container<int,         container::set>::type    ws;
    wrap_into_container<double,      container::list>::type   wl;
    wrap_into_container<bool,        container::deque>::type  wd;
    wrap_into_container<std::string, container::vector>::type wv;


    return ws.size() + wl.size() + wd.size() + wv.size();

}

See it Live On Coliru



来源:https://stackoverflow.com/questions/23119046/c-template-allocator-for-template-container

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!