使用模板 class 作为参数编写函数的 C++ 快捷方式

C++ shortcut for writing function with template class as a parameter

在大多数特定模板参数无关紧要的情况下,是否有编写将模板化 class 作为参数的函数的快捷方式?

给定

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 无关紧要。有没有办法避免写

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 到 E 的默认值的实例化。

尝试可变参数模板:

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

对于这个声明,有多少模板参数以及它们的类型是什么并不重要。唯一的限制是 xy 必须使用同一组类型实例化。如果不需要此限制,请参阅 Yakk 的回答。如果需要,它还允许您编写部分专业化。

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)

也许你可以将指标声明为

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