2015-10-22 35 views
6

我想知道是否有可能檢測模板類容器類型,並重新定義其參數。例如:是否可以在C++中提取容器模板類?

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

其中vdouble現在是std::vector<double>

回答

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

這將爲在陽光下的容器中工作。

+0

爲什麼不能用於std :: array? –

+1

@Benoît因爲它具有值模板參數,所以在這種情況下必須修改這個類。 – CoffeeandCode

+0

嗯,我從來沒有想過typename ...這個事實只是擴展到類型,這是顯而易見的。謝謝。 –

7

是的,你可以做一個簡單的模板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>; 

現在T2std::vector<double>

+0

唉,這隻適用於矢量,整個想法是爲模板類,列表,地圖,mylist等...沒有rebinder每個人。 – g24l

+0

有一件麻煩事,你會改變向量的類型,但不是分配器類型。在開始時,你的向量包含'int'類型的值和'std :: allocator '類型的分配器。在這裏您將值類型更改爲double,但不是分配器類型。導致: 值類型:雙重 分配器類型:std :: allocator 示例http://coliru.stacked-crooked.com/a/2c8d57b2736947ee顯示錯誤。我們有一個std :: vector > – Pumkko

+0

@Pumkko:啊,是的,這確實是一個可怕的想法。讓我改變這一點。 –

相關問題