我想知道是否有可能檢測模板類容器類型,並重新定義其參數。例如:是否可以在C++中提取容器模板類?
typedef std::vector<int> vint;
typedef typeget<vint>::change_param<double> vdouble;
其中vdouble現在是std::vector<double>
?
我想知道是否有可能檢測模板類容器類型,並重新定義其參數。例如:是否可以在C++中提取容器模板類?
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...>;
};
這將爲在陽光下的容器中工作。
是的,你可以做一個簡單的模板rebinder使用部分專業化:
#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>
。
唉,這隻適用於矢量,整個想法是爲模板類,列表,地圖,mylist等...沒有rebinder每個人。 – g24l
有一件麻煩事,你會改變向量的類型,但不是分配器類型。在開始時,你的向量包含'int'類型的值和'std :: allocator
@Pumkko:啊,是的,這確實是一個可怕的想法。讓我改變這一點。 –
爲什麼不能用於std :: array? –
@Benoît因爲它具有值模板參數,所以在這種情況下必須修改這個類。 – CoffeeandCode
嗯,我從來沒有想過typename ...這個事實只是擴展到類型,這是顯而易見的。謝謝。 –