簡體   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