c++多类型模板使用指南
C++ Multi-Type Template Use Guidelines
我正在寻找如何在c++中使用模板设计多类型泛型算法的指南。
对我来说,一个反复出现的问题是,例如,是否要写一个像这样的简化函数
template <typename Container, typename Element>
E reduce_something(const Container<Element> & a)
{
// ...
}
或者像这样跳过元素类型
template <typename Container>
Container::element_type reduce_something(const Container & a)
{
// ...
}
以及何时使用嵌套模板。
作为指导原则,我通常尽量确保对模板类型施加尽可能少的需求和限制。
template <typename Container, typename Element>
E reduce_something(const Container<Element> & a)
{
// ...
}
这是不正确的,它应该是这样的:
template < template<typename> class Container, typename Element>
Element reduce_something(const Container<Element> & a)
{
// ...
}
但是这给Container
增加了很多要求。它必须只接受一个模板参数,所以像std::vector
这样的东西不能这样做,因为它有一个分配器模板参数。我可以用一个非模板类型Container
编写一个模板函数,而不假设它是一个模板类型,如果我想与Element
交互的操作在模板实例化时完成,那么一切都会正常工作。
template <typename Container>
Container::element_type reduce_something(const Container & a)
{
// ...
}
这增加了Container
必须包含element_type
类型成员的关键要求。最好使用trait类,这样你就可以为标准容器(有value_type
代替)和其他你不能直接修改的类型创建trait。
可能更好的方法是使用由迭代器分隔的范围。例如
#include <iterator>
template<InputIterator>
typename std::iterator_traits<InputIterator>::value_type
reduce_something(InputIterator first, InputIterator last)
{
// ...
}
已经有一个合适的标准性状类,该算法将与子范围、由指针分隔的范围和所有类型的容器一起工作。
您是否考虑过传入并返回一个或多个迭代器类型的规范c++方法?在这种情况下,传入start和end来指定范围,并为返回值使用相同类型或不同的迭代器类型。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- C++:TypeDef使用元组
- 使用std::multimap迭代器创建std::list
- 从不同线程使用int64的不同字节安全吗
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么在全局范围内使用"extern int a"似乎不行?
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用Google Mock来模拟gettimeofday()
- 如何使用默认参数等选择模板专业化
- 为什么在使用typedef时类推导指南会失败
- 如何将GTest与CMake一起使用?遵循谷歌指南时的链接问题
- 如何对多个模板参数使用用户定义的推导指南
- 如何使用模板处理多类型变量?
- 如何使用模板化构造函数定义演绎指南?
- 什么是模板扣除指南,何时应该使用它们
- 使用类/构造函数的指南
- C3857不允许使用多类型参数列表编译器错误
- c++多类型模板使用指南
- 如何使用模板编程创建多类型数组