当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - How to re-specialize a template?

问题描述:

I have a template:

template<class T>

and I expect T to be a specialized container, for example, std::array<int, 5>.

And, having this std::array<int, 5>, I would like to somehow craft a type that would look like this: std::array<std::pair<bool, int>, 5>.

Is it possible?

I suppose, if I could somehow extract a pure, unspecialized std::array from std::array<int, 5>, and the parameters specializing this std::array as a parameter pack, I could do it like this:

template<typename Container, typename T, typename ...Rest>

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

using respecialized_container =

rc<unspecialized_container, container_parameters>;

But, to do this, I need to have this unspecialized_container and container_parameteres...

Is there any way I can do this?

网友答案:

Here's a partial approach that works for both std::array and the simple standard library containers (the ones that take exactly two parameters):

#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>>;
};

Now given, say, T = std::array<int, 5>, you get

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

and given U = std::list<float>, you get

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

You can extend this to other container class templates on a case by case basis by adding partial specializations of boolpair_rebind.

分享给朋友:
您可能感兴趣的文章:
随机阅读: