2016-11-19 73 views
1

我有一個模板:如何重新專門化模板?

template<class T> 

,我希望T是一個專門的容器,例如,std::array<int, 5>

而且,有這std::array<int, 5>,我想以某種方式製作一個看起來像這樣的類型:std::array<std::pair<bool, int>, 5>

可能嗎?

我想,如果我能以某種方式提取純,非特std::arraystd::array<int, 5>和專業這std::array作爲參數組的參數,我能做到這一點是這樣的:

template<typename Container, typename T, typename ...Rest> 
using rc = Container<std::pair<bool, T>, Rest...>; 

using respecialized_container = 
    rc<unspecialized_container, container_parameters>; 

但是,要做到這一點,我需要有這個unspecialized_containercontainer_parameteres ...

有沒有什麼辦法可以做到這一點?

+2

這很容易只是'array'做,但一般很難,因爲你的客戶端模板可以有兩種類型,非類型參數,這是很難一概而論了。另外,您需要重新綁定動態容器的分配器參數。 –

+3

我們不會將[tag:C++]標籤編輯到您的問題中,因爲這很有趣;我們正在這樣做,因爲我們希望_you_開始正確標記您的問題。採取提示! –

+1

@LightnessRacesinOrbit好的,我會的。 Outta簡單的好奇心,你是否記得我在那麼多SO用戶當中,還是你有一些潛在有問題的用戶列表,只有高級的退伍軍人才能看到,而且我恰好被放在那個名單上,因爲他們忘記了添加C++標籤? – gaazkam

回答

4

下面是兩個std::array和簡單的標準庫中的容器(即正好用兩個參數的)工作的部分方法:

#include <array> 
#include <memory> 
#include <utility> 

template <typename> struct boolpair_rebind; 

template <typename C> using boolpair_rebind_t = typename boolpair_rebind<C>::type; 

template <typename T, std::size_t N> 
struct boolpair_rebind<std::array<T, N>> 
{ 
    using type = std::array<std::pair<bool, T>, N>: 
}; 

template <typename T, typename Alloc, template <typename, typename> class DynCont> 
struct boolpair_rebind<DynCont<T, Alloc>> 
{ 
    using NewT = std::pair<bool, T>; 
    using type = DynCont< 
        NewT, 
        typename std::allocator_traits<Alloc>::rebind_alloc<NewT>>; 
}; 

現在給出,比如說,T = std::array<int, 5>,你

boolpair_rebind_t<T> = std::array<std::pair<bool, int>, 5>; 

並給予U = std::list<float>,你

boolpair_rebind_t<U> = std::list<std::pair<bool, int>>; 

您可以通過添加boolpair_rebind的部分特化來逐個將其擴展到其他容器類模板。