如何在不将代码放入头文件的情况下处理任何迭代器

How to handle any iterator without putting the code in the header file?

本文关键字:文件 情况下 处理 迭代器 任何 代码      更新时间:2023-10-16

问题如下:

头文件(库的API的一部分):

template <typename IterType>
void foo(const IterType &begin, const IterType &end);

CPP文件:

template <typename IterType>
void my_really_large_implementation_specific_function(const IterType &begin, const IterType &end) {
    // ...
}

是否可以使foo()调用my_really_large_implementation_specific_function()而不在头文件中包含my_really_large_implementation_specific_function()的代码,也不生成其模板的多个实例?也许使用某种包装迭代器类,但我不确定如何使用。

请在此处查看使用Boost中包含的any_iterator的示例。范围:http://geek-cpp.blogspot.fr/2012/11/using-boost-anyiterator-to-hide.html

#include <string>
// note that there is no include to multi_index here! 
#include <boost/scoped_ptr.hpp>
#include <boost/range/concepts.hpp>
#include <boost/range/detail/any_iterator.hpp>
class hidden_container; //forward declare the hidden container
class exemple {
public:
  boost::scoped_ptr<hidden_container> impl; //hidden container behind pointer
  // declare a type erased iterator that can iterate over any container of std::string
  // this could be a std::vector<std::string>::const_iterator or a     std::list<std::string>::const_iterator
  typedef boost::range_detail::any_iterator<
         const std::string,
         boost::forward_traversal_tag,
         const std::string&,
         std::ptrdiff_t
         > const_iterator;
  //ctor
  exemple();
  // abstracted iterators
  const_iterator begin() const;
  const_iterator end() const;
};

您看过boost::any_range吗?它使用类型擦除来隐藏模板类型,并使用虚拟方法调用作为交换。

如果您希望函数能够在任意迭代器类型上操作,那么主体需要出现在头部中。

如果只需要支持一个迭代器类型,那么它不需要是模板,并且可以出现在源文件中。

也许你只是想做一个for_each?

// In the header:
void my_really_large_implementation_specific_function(const common_base_class& c);
template <typename IterType>
void foo(const IterType &begin, const IterType &end)
{
   std::for_each(begin, end, my_really_large_implementation_specific_function);
}
相关文章: