C++以模板类作为参数编写函数的快捷方式

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

本文关键字:函数 快捷方式 参数 C++      更新时间:2023-10-16

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

鉴于

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<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

尝试可变参数模板:

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

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