我不确定我是否理解这个问题,但无论如何我都试图模拟别名模板的专业化。
我假设这个想法是将别名模板限制为某些(模式匹配类型);我们曾经用这种代码做的事情:
template<class Vector> struct old_style;
template<class T> struct old_style<std::vector<T> >{
typedef typename std::vector<T>::value_type type;
};
(这只是一个示例,还有其他方法可以提取通用std::vector 的value_type)。
现在是别名:
template<class Vector> using new_style = typename Vector::value_type;
它做同样的工作,但这并不能取代old_stype<...>::type,因为它没有那么严格。第一次尝试有一个完美的别名替换是这个假设的代码:
//template<class Vector> using new_style2; // error already here
//template<class T> using new_style2<std::vector<T> > = typename Vector::value_type;
不幸的是,它没有编译(理论上由于其他答案和标准中所述的名义原因,在实践中我想这没有根本原因成为限制)。幸运的是,可以退回到老式的 struct::type 方式,只使用新的别名模板功能来转发工作,
template<class Vector> struct new_style2_aux;
template<class T> struct new_style2_aux<std::vector<T> >{
typedef typename std::vector<T>::value_type type;
};
template<class Vector> using new_style2 = typename new_style2_aux<Vector>::type;
可以使用define 使其自动化
#define SPECIALIZED_ALIAS_TEMPLATE(NamE, Pattern_arG, PatterN_expR, DefinitioN) \
template<class> struct NamE ## _aux; \
template<Pattern_arG> struct NamE ## _aux<PatterN_expR>{ \
typedef DefinitioN type; \
}; \
template<class NamE ## _dummy> using NamE = typename NamE ## _aux< NamE ## _dummy >::type;
可以用作:
SPECIALIZED_ALIAS_TEMPLATE(new_style3, class T, std::vector<T>, typename std::vector<T>::value_type);
如果需要任意数量的特化(或代码中的非局部特化),则必须在两部分中使用更复杂的define,一部分用于声明,另一部分用于特化(应该如此):
#define DECLARE_ALIAS_TEMPLATE(NamE)\
template<class> struct NamE ## _aux;\
template<class NamE ## _dummy> using NamE = typename NamE ## _aux< NamE ## _dummy >::type;
#define SPECIALIZE_ALIAS_TEMPLATE(NamE, Pattern_arG, PatterN_expR, DefinitioN)\
template<Pattern_arG> struct NamE ## _aux<PatterN_expR>{ \
typedef DefinitioN type; \
};
如下使用:
DECLARE_ALIAS_TEMPLATE(new_style4);
SPECIALIZE_ALIAS_TEMPLATE(new_style4, class T, std::vector<T>, typename std::vector<T>::value_type);
SPECIALIZE_ALIAS_TEMPLATE(new_style4, class T, std::set<T>, typename std::set<T>::value_type);
以上所有代码都可以复制粘贴进行测试:
#include<vector>
#include<map>
// ... paste code above //
int main(){
old_style<std::vector<double> >::type a; // is a double
// old_style<std::set<double> >::type a; // error (should work only for std::vector)
new_style2<std::vector<double> > b; // is double
// new_style2<std::set<double> > c; // error (should work only for std::vector)
new_style3<std::vector<double> > d; // is double
// new_style3<std::set<double> > d; // error (should work only for std::vector)
new_style4<std::vector<double> > e; // is double
new_style4<std::set<double> > f; // is double, this is another specialization
return 0;
}
对不起,如果这不是您要找的。我相信它可以与可变参数模板和额外的模板参数(在专业化中)一起使用,但没有测试它。
非常欢迎改进。