2014-04-16 25 views
1

在我的C++模板結構中,我想使用不同的容器類型,它們使用不同的分配器,例如, std :: vector和thrust :: device_vector。C++模板:模板容器的分配器

我需要明確地指定分配,否則我得到「錯誤號碼的模板參數(1,應該是2)」:

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

由於不同的容器類使用不同的分配器,我必須指定每次我想使用這個模板時,相應的分配器。

如何根據Container類型獲取分配器而無需指定它?

我想用一個特徵結構,然後我專門爲每個容器的類型,但我不知道如何實現它,或者如果它甚至有用/可能/ ...

更新: 我不能使用C++ 11遺憾的是,由於NVIDIA的編譯器的限制......

回答

4

在C++ 11,我喜歡variadics

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

我沒有檢查是否C::type實際上是一個簡潔(wellformed) expre裂變標準容器類型

到註釋:

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

+0

我不能使用C++ 11,I在上面的問題添加此。我也不知道這將如何讓我不必指定分配器? –

+0

等一下。我假設你需要**在外部傳遞分配器。我不是,讓我編輯! – sehe

+0

你是對的,C :: type是一個錯誤,與其他一些metafunctions混淆:) –