我想根据模板的内部参数专门化模板。我正在使用非严格的评估,这让事情变得困难。
特化应该基于最少嵌套的模式匹配。例如:
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
我该怎么做?
您可以只使用模板模板参数:
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) .
我是一名优秀的程序员,十分优秀!