Home > OS >  Iterate over two possible types of iterable objects C
Iterate over two possible types of iterable objects C

Time:02-23

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?

CodePudding user response:

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.).

  • Related