c++ - 如何重新专门化模板?

标签 c++ c++11 templates template-specialization

我有一个模板:

template<class T>

我希望 T成为一个专门的容器,例如 std::array<int, 5> .

并且,有了这个 std::array<int, 5> ,我想以某种方式制作一个看起来像这样的类型:std::array<std::pair<bool, int>, 5> .

这可能吗?

我想,如果我能以某种方式提取一个纯粹的、非特化的 std::array来自 std::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 ...

有什么办法可以做到这一点吗?

最佳答案

这是适用于 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 的部分特化将其扩展到其他容器类模板.

关于c++ - 如何重新专门化模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40696270/

相关文章:

c++ - 类不存在默认构造函数

c++ - 自定义类中的 move 与复制性能

函数执行器中的 C++ 歧义,参数在 vector 中传递

c++ - 已删除 "general"案例的专用模板函数无法使用 g++ <=4.8.0 和 clang++ 编译

使用 const 和 & 的 C++ 模板化函数包装器参数

c++ - 有条件地禁用复制构造函数

c++ - OpenGL 状态集

c++ - pthread 在一定时间后终止

c++ - 我应该链接什么来定义 boost::thread_specific_ptr 及相关内容?

c++ - 返回一个右值——这段代码有什么问题?