繁体   English   中英

c ++ template:模板容器的分配器

[英]c++ template: allocator for template container

在我的c ++模板struct中,我想使用使用不同分配器的不同容器类型,例如std :: vector和推力:: device_vector。

我需要显式地指定分配器,否则会收到“模板参数数量错误(1,应为2)”:

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

由于不同的容器类使用不同的分配器,因此我每次使用此模板时都必须指定相应的分配器。

如何在不指定容器的情况下根据容器类型获取分配器?

我考虑过使用一种特质结构,然后专门针对每种容器类型,但是我不知道如何实现它,或者它是否有用/可能/ ...

更新:由于NVIDIA编译器的限制,我无法使用C ++ 11 ...

在c ++ 11中,我赞成variadics

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

我没有检查C::type是否实际上是标准容器类型的格式正确的表达式

发表评论:

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

对于C ++ 03,您可以使用嵌套的typedef来模拟模板别名,从本质上讲,是使一元类型函数接受单个元素类型并返回该类型的容器。 这个概念:

#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();

}

在Coliru上实时观看

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM