我有一个模板:
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_container
和 container_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/