2012-01-25 67 views
1

我想基於其內部參數專門化模板。我正在使用非嚴格的評估,這使得事情變得困難。基於嵌套內部參數的專用模板

專業化應該基於最少的嵌套模式匹配。例如:

template<typename T> 
struct data1; 

template<typename T> 
struct fun1 { 
    using type = data1<T>; 
}; 

template<typename T> 
struct fun2; 
template<typename T> 
struct fun2<data1<T>> { 
    using type = data1<T>; 
}; 

fun2<data1<int>> x1;    // this works as expected, T=int 
fun2<data1<fun1<int>>>::type x2; // this works as expected, T=fun1<int> 
fun2<fun1<int>>::type x3;  // this should be specialized as fun2<data1<int>>, T=int 
fun2<fun2<fun1<int>>>::type x4; // this should be specialized as fun2<data1<int>>, T=int 

我該怎麼做?

回答

1

你可以只用一個模板的模板參數:

template<typename T> 
struct data1; 

template<typename T> 
struct fun1 { 
    using type = data1<T>; 
}; 

template<typename T> 
struct fun2; 

template<class T> 
struct fun2<data1<T>>{ 
    using type = data1<T>; 
}; 

template<template<class> class X, class T> 
struct fun2<X<T>> 
    : fun2<typename X<T>::type>{}; 

測試:

#include <type_traits> 

static_assert(std::is_same<fun2<data1<int>>::type, data1<int>>::value, "fun2<data1<int>>"); 
static_assert(std::is_same<fun2<data1<fun1<int>>>::type, data1<fun1<int>>>::value, "fun2<data1<fun1<int>>>"); 
static_assert(std::is_same<fun2<fun1<int>>::type, data1<int>>::value, "fun2<fun1<int>>"); 
static_assert(std::is_same<fun2<fun2<fun1<int>>>::type, data1<int>>::value, "fun2<fun2<fun1<int>>>"); 

int main(){ 
} 

Live example on Ideone (with using-aliases changed to typedefs)