自定义迭代器指向临时对象(延迟加载)
Custom iterator to point to a temporary object (lazy loading)
我有以下 class:
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;
};
这是一个应该提供延迟加载文件的接口。此 class 的实现将获取可读路径列表并按需读取文件。 class 的示例用法如下:
Reader reader; // Reader implements IReader
for(auto path : reader)
{
auto decodedFile = reader.read(path);
imshow(decodedFile);
}
然而,这看起来有点奇怪 - 作为此 class 的用户,我不需要知道它存储的文件名。如果我能像下面这样使用这个 class 就方便多了:
Reader reader; // Reader implements IReader
for(auto file : reader)
{
imshow(*file);
}
是否有可能在 C++ 中设计 IReader class 使其像上一个代码片段中那样可迭代?
创建某种简单的惰性资源 class 是最简单的。然后,您可以轻松地制作这些容器(std::vector<LazyFile>
等),或者使用它来构建自定义 iterator/container 以满足您的需求。一次解决一个问题。
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
我有以下 class:
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;
};
这是一个应该提供延迟加载文件的接口。此 class 的实现将获取可读路径列表并按需读取文件。 class 的示例用法如下:
Reader reader; // Reader implements IReader
for(auto path : reader)
{
auto decodedFile = reader.read(path);
imshow(decodedFile);
}
然而,这看起来有点奇怪 - 作为此 class 的用户,我不需要知道它存储的文件名。如果我能像下面这样使用这个 class 就方便多了:
Reader reader; // Reader implements IReader
for(auto file : reader)
{
imshow(*file);
}
是否有可能在 C++ 中设计 IReader class 使其像上一个代码片段中那样可迭代?
创建某种简单的惰性资源 class 是最简单的。然后,您可以轻松地制作这些容器(std::vector<LazyFile>
等),或者使用它来构建自定义 iterator/container 以满足您的需求。一次解决一个问题。
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