指向临时对象的自定义迭代器(延迟加载)
Custom iterator to point to a temporary object (lazy loading)
我有以下类:
template <class T>
class IReader
{
using const_iterator = std::vector<filesystem::Path>::const_iterator;
public:
virtual ~IReader() = default;
virtual T read(const_iterator path) const = 0;
virtual const_iterator begin() const = 0;
virtual const_iterator end() const = 0;
virtual size_t size() const = 0;
};
这是一个应该提供延迟加载文件的界面。此类的实现将获取可读路径列表并按需读取文件。此类的考试用法如下:
Reader reader; // Reader implements IReader
for(auto path : reader)
{
auto decodedFile = reader.read(path);
imshow(decodedFile);
}
然而,这看起来有点奇怪 - 作为这个类的用户,我不需要知道它存储了什么文件名。如果我能按如下方式使用这个类会方便得多:
Reader reader; // Reader implements IReader
for(auto file : reader)
{
imshow(*file);
}
C++,是否有可能像上一个代码片段那样以可迭代的方式设计 IReader 类?
创建某种简单的惰性资源类将是最简单的。然后,您可以轻松制作这些容器(std::vector<LazyFile>
等(,或者使用它来构建自定义迭代器/容器以满足您的需求。一次解决一个问题。
template<class T> class LazyFileInput
{
public:
LazyInputFile(const std::string &path)
: path(path), data(), loaded(false);
const T &get()
{
std::unique_lock<std::mutex> lock(mutex);
if (!loaded) load_file();
return data;
}
private:
std::string path;
T data;
std::mutex mutex;
bool loaded;
void load_file()
{
// TODO: Implement this however you want to load your T data.
std::ifstream fs(path);
fs >> data;
loaded = true;
}
};
// Is a custom iterator even needed at this point? Certainly a seperate problem however.
std::vector<LazyFileInput> files;
std::unordered_map<std::string, LazyInputFile> images; // image name -> image
相关文章:
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++中带有List类的迭代器Segfault
- 如何在c++迭代器类型中包装std::chrono
- 集合上的输出迭代器:assign和increment迭代器
- Boost Spirit,获取迭代器内部语义动作
- 对于set上的循环-获取next元素迭代器
- 为什么output_editor Concept不需要output_e迭代器标记
- c++17文件系统::recursive_directory迭代器()在mac上没有给出这样的目录,但在windows上
- 使用迭代器时如何访问对象在向量中的位置?
- std::vector::迭代器是否可以合法地作为指针
- 跟随整数索引列表的自定义类迭代器
- 不明白迭代器,引用和指针失效,一个例子
- 我可以使用反向迭代器作为ForwardIt吗
- 指向临时对象的自定义迭代器(延迟加载)
- 矢量迭代器在 Visual Studio 中不可延迟
- 编译器优化会中断延迟迭代器
- C++按需加载元素的容器的随机访问迭代器
- 是否有任何链接器标志告诉在打开后延迟加载动态库
- 仅visual studio 2010中存在可延迟迭代器问题