2016-11-19 99 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的部分特化来逐个将其扩展到其他容器类模板。