2016-07-14 43 views
0

当大多数特定的模板参数无关紧要时,是否有写入将模板类作为参数的函数的快捷方式?以模板类作为参数编写函数的C++快捷方式

鉴于

template<typename A, typename B, typename C, typename D, typename E> 
class Foo 

我想写

template<typename A> 
int metric(Foo<A> x, Foo<A> y) 
在这种情况下

,模板参数B到E无关。有没有一种方法,以避免到E写

template<typename A, typename B, typename C, typename D, typename E> 
int metric(Foo<A, B, C, D, E> x, Foo<A, B, C, D, E> y) 

参数B已经违约,但我想度量的所有实例的工作,而不仅仅是通过E.使用B的默认值

回答

4
template<class A, class...Ts,class...Us> 
int metric(Foo<A, Ts...> x, Foo<A, Us...> y) 

这允许两个Foo类型不同。如果你想在同一只:

template<class A, class...Ts> 
int metric(Foo<A, Ts...> x, Foo<A, Ts...> y) 
+0

有没有一种方式,如果一个做到这一点的模板参数是值而不是类型名(例如,'template ')? – Zack

+1

@zack不是真的。如果您想要良好的元编程支持,请避免使用非类型的模板参数 – Yakk

0

尝试可变参数模板:

template<typename A, typename ... others> 
int metric(Foo<A, others...> x, Foo<A, others...> y) 

对于此声明,无论有多少模板参数以及它们的类型如何。唯一的限制是,xy必须使用相同的一组类型实例化。如果这个限制是不需要的,请参阅Yakk的答案。如果需要,它也允许你写部分专业化。

0

也许你可以声明度量作为

template<typename T> 
int metric(T x, T y) 

然后模板参数推导应该工作:

Foo< whatever parameters > f,g; 
int x = metric(f,g);   // no need to specify parameters again