c++多类型模板使用指南

C++ Multi-Type Template Use Guidelines

本文关键字:使用指南 多类型 c++      更新时间:2023-10-16

我正在寻找如何在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来指定范围,并为返回值使用相同类型或不同的迭代器类型。