是否可以在 c++ 中提取容器模板类

Is it possible to extract in c++ the container template class?

本文关键字:提取 c++ 是否      更新时间:2023-10-16

我想知道是否可以检测模板类容器类型,并重新定义其参数。例如:

typedef std::vector<int> vint;
typedef typeget<vint>::change_param<double> vdouble;

vdouble现在在哪里会成为std::vector<double>

除了@Kerrek SB的答案之外,这里是通用方法:

template<typename...> struct rebinder;
template<template<typename...> class Container, typename ... Args>
struct rebinder<Container<Args...>>{
    template<typename ... UArgs>
    using rebind = Container<UArgs...>;
};

这将适用于阳光下的任何容器。

是的,您可以使用部分专用化制作一个简单的模板重新绑定器:

#include <memory>
#include <vector>
template <typename> struct vector_rebinder;
template <typename T, typename A>
struct vector_rebinder<std::vector<T, A>>
{
    template <typename U>
    using rebind =
        std::vector<U,
                    typename std::allocator_traits<A>::template rebind_alloc<U>>;
};

用法:

using T1 = std::vector<int>;
using T2 = vector_rebinder<T1>::rebind<double>;

现在T2 std::vector<double>.