我想根据内部参数来专门化模板。我正在使用非严格的评估,这使得事情变得困难。
专业化应该基于最少嵌套的模式匹配。例如:
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
我该怎么做?
答案 0 :(得分: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)