The following piece of code aims to strip the first part of a path in case it exists:
#include <filesystem>
std::filesystem::path strip_prefix(std::filesystem::path p)
{
if (auto it{p.begin()}; it != p.end())
{
++it;
return std::filesystem::path(it, p.end());
}
return p;
}
(See: https://godbolt.org/z/wkXhcw)
I was surprised to find out this does not work. The code does not compile since the path constructor only takes iterators that iterate over character sequences. I can see the use of that, but why limit construction to only those kind of iterators? In my opinion it is counter intuitive to not support constructing a path from its own iterators. As far as I know most other STL types do support this idiom.
What would be an efficient implementation to achieve the same goal, other than completely reconstructing a new path?
Update: in this context, I found the following discussion relevant/amusing: http://boost.2283326.n4.nabble.com/boost-filesystem-path-frustration-td4641734.html. I agree with Dave here. I think seeing a path as a container of path elements is a very natural way to look at it (from a programmer's perspective).