如何在不将代码放入头文件的情况下处理任何迭代器
How to handle any iterator without putting the code in the header file?
问题如下:
头文件(库的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);
}
相关文章:
- 为什么在某些情况下不写入此文件?
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 有没有办法在不使用 getline() 的情况下从.csv文件中读取?
- 是否可以在没有真实文件的情况下创建 ifstream
- 在 c++ 中连接字符串和整数,以便在 C++ 11 不支持计算机的情况下读取多个文件
- 如何在多写入器情况下对文件支持的共享内存中的大页面出错
- 如何在添加文件的情况下在VSCode中调试C++程序
- 每个文件(理想情况下是每个部分)的 clang 格式样式覆盖
- 如何在不重新创建现有文件的情况下写入.txt文件
- 如何在不知道大小的情况下读取文本文件并存储到数组中
- 如何使用Winforms C#或C++.Net在不更改文件中其他内容的情况下修改jpg文件中的Orientation e
- 如何在不循环的情况下使用getline读取文件
- 在不打开应用程序的情况下在MinGW c++中播放声音(.wav)文件
- C++-在没有自定义.lib文件的情况下从Lua C模块调用Lua函数
- 如何在不使用文件扩展名的情况下使用命令行参数打开C++中的文本文件?
- 如何在不受其他文件影响的情况下"by itself" Visual Studio 项目中运行C++文件?
- 如何在不包含完整的文件系统头的情况下使用文件系统的类路径C++17?
- 如何在不设置 ulimit -n 的情况下解决套接字程序打开太多文件的错误
- Nlohmann 在不知道密钥的情况下解析 JSON 文件
- C++:如何在不将命令传递给 shell 的情况下执行文件?