C++ 模板 : allocator for template container

标签 c++ templates stl containers

在我的 C++ 模板结构中,我想使用使用不同分配器的不同容器类型,例如std::vector 和 thrust::device_vector。

我需要明确指定分配器,否则我会得到“错误的模板参数数量(1,应该是 2)”:

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

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

如何根据容器类型获取分配器而无需指定?

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

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

最佳答案

在 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++ 模板 : allocator for template container,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23119046/

相关文章:

c++ - 什么类型的 API 或算法用于生成 session ID?

c++ - C++中指针的地址

c++ - std::list::clear 是否使 std::list::end 迭代器无效?

c++ - 如何在 std::map 中存储混合类型项目?

c++ - 重载 C++ STL 方法

c++ - 如果输入错误则无限循环

用于发出 HTTPS 请求的 C++ 高级网络库

c++ - 如何为输入和输出参数使用单独的参数包?

c++ - 使用模板指定成员变量

c++ - 添加带有参数包扩展的所有参数