C++以模板类作为参数编写函数的快捷方式
C++ shortcut for writing function with template class as a parameter
当
大多数特定模板参数无关紧要时,是否有快捷方式可以编写将模板化类作为参数的函数?
鉴于
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)
对于此声明,有多少模板参数以及它们的类型并不重要。唯一的限制是x
和y
必须使用相同的类型集进行实例化。如果不需要此限制,请参阅Yakk的答案。此外,如果需要,它还允许您编写部分专业化。
相关文章:
- 如何在c++中为模板函数实例创建快捷方式
- C++ ->运算符 [] 的快捷方式
- C++结构模板变量快捷方式定义不起作用
- 请描述一下在 c++ 中在此类中定义构造函数的方式?
- 用于基于成员字段或函数创建比较器的快捷方式
- c++ Visual Studio 2015 快捷方式,用于从选择代码中生成功能
- 是否有用于"go to variable type definition" C++中"auto"变量的 Visual Studio 键盘快捷方式?
- Qt全局快捷方式扩展劫持快捷方式
- 在Qt Creator中应用代码更改的快捷方式是什么?
- 是否有快捷方式重叠运算符?
- 使用 C++ 显示 (.lnk) 快捷方式文件的真实路径
- 一个按钮有两个或多个快捷方式
- 通过TranslateAccelerator检测快捷方式时,忽略Shift键的状态
- 无论如何,是否可以确定MFC应用程序是通过PC重新启动或用户单击应用程序快捷方式开始的
- 为什么我以前调用析构函数的方式会导致模因问题
- QDIR入口列表可以使用文件夹快捷方式透明地工作
- C++成员函数定义类前缀快捷方式(也是模板)
- 构造函数的快捷方式
- 复制构造函数快捷方式
- C++以模板类作为参数编写函数的快捷方式