指向临时对象的自定义迭代器(延迟加载)

Custom iterator to point to a temporary object (lazy loading)

本文关键字:延迟加载 迭代器 自定义 临时对象      更新时间:2023-10-16

我有以下类:

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