【问题标题】:c++ template: allocator for template containerc ++模板:模板容器的分配器
【发布时间】:2014-04-16 20:02:40
【问题描述】:

在我的 c++ 模板结构中,我想使用使用不同分配器的不同容器类型,例如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++ templates stl containers


    【解决方案1】:

    在 c++11 中,我喜欢可变参数

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

    Live On Coliru

    【讨论】:

    • 我不能使用 C++11,我在上面的问题中添加了这个。我也看不出这如何让我不必指定分配器?
    • 等等。我假设您需要“在外部”传递分配器。我没有,让我编辑!
    • 你是对的,C::type 是一个错误,与其他一些元函数混淆了:)
    • @m.s. this 有帮助吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-11
    • 1970-01-01
    • 1970-01-01
    • 2011-06-22
    • 1970-01-01
    相关资源
    最近更新 更多