Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Iterate over two possible types of iterable objects C++

I’d like a program of mine to be flexible and for it to either be able to iterate over a list of files in a directory for which I’m currently using

        for(const auto& dirEntry : fs::directory_iterator(input_dir))

where fs is filesystem.
I’d also like the possibility of iterating over a vector of strings, and to choose between these two different types at runtime. however my best idea so far is to just have two different for loops and choosing the correct one with an if/else statement but that feels like a poor coding choice.
Is there any way to generically iterate over one or the other?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can extract the code with the loop into a template, e.g.

template<class Range> void DoWork(Range&& dirEntries)
{
    for (const auto& dirEntry : dirEntries)
        ; // ...
}

and then instantiate/call the template with

DoWork(fs::directory_iterator(input_dir));

or

DoWork(myVectorOfStrings);

Note that whatever you do in the loop body must work with whatever element type the range has (std::string, fs::path etc.).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading