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

g24*_*24l 6 c++ templates traits

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

typedef std::vector<int> vint;
typedef typeget<vint>::change_param<double> vdouble;
Run Code Online (Sandbox Code Playgroud)

vdouble现在在哪里std::vector<double>

Cof*_*ode 10

再加上@Kerrek SB的答案,这是通用的方法:

template<typename...> struct rebinder;

template<template<typename...> class Container, typename ... Args>
struct rebinder<Container<Args...>>{
    template<typename ... UArgs>
    using rebind = Container<UArgs...>;
};
Run Code Online (Sandbox Code Playgroud)

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


Ker*_* SB 7

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

#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>>;
};
Run Code Online (Sandbox Code Playgroud)

用法:

using T1 = std::vector<int>;

using T2 = vector_rebinder<T1>::rebind<double>;
Run Code Online (Sandbox Code Playgroud)

现在T2std::vector<double>.