I want to use methods std::filesystem::directory_iterator or std::filesystem::recursive_directory_iterator depending on a boolean. The code would be something like:
some_type dirIterator = isRecursive ? std::filesystem::recursive_directory_iterator : std::filesystem::directory_iterator;
for (const std::filesystem::directory_entry& entry : dirIterator(path))
{
// common code for the two iterators
}
How can I accomplish this? If there are different approaches I would like to know all to choose the one I like more, but I think I prefer the simpler one :-)
I tried to use a function pointer but I do not know the "common" return type of the two iterators:
??? (*dirIterator) (const std::filesystem::path & dirPath);
recursive_directory_iteratoranddirectory_iteratorare distinct types, and they are not covariant. If you try to select one of two with the conditional? A : Boperator, there is a problem, sinceAandBare unrelated types.Template-based solution
However, both types of iterators share a common interface. Most importantly, they are iterable. This suggests that you could use templates to solve the problem.
Non-template solutions
Another solution is to put whatever you were going to do in the loop into a lambda:
This produces mild code duplication, but it's conceptually simpler than the template.
A clever solution by commenter @Turtlefight is to use
recursive_diretory_iteratorin both cases, and disable recursion after each iteration withdisable_recursion_pending: