Consider the following assertions about path decomposition, where each local variable e.g. stem
has the obvious initialization e.g. auto stem = path.stem()
—
assert(root_path == root_name / root_directory);
assert(path == root_name / root_directory / relative_path);
assert(path == root_path / relative_path);
assert(path == parent_path / filename);
assert(filename == stem + extension);
This all works, except for the last line — because fs::path
does not define an operator+
. It has operator+=
, but no operator+
.
What's the story here?
I've determined that I can make this code compile by adding my own operator+
. Is there any reason not to do this? (Notice this is in my own namespace; I'm not reopening namespace std
.)
fs::path operator+(fs::path a, const fs::path& b)
{
a += b;
return a;
}
My only hypotheses on the subject are:
Maybe the designers worried that
operator+
would be too easily confused withstd::string
'soperator+
. But that seems silly, since it does exactly the same thing semantically (so why care if it gets conflated?). And it also seems that the designers didn't care about newbies' confusion when they designedpath.append("x")
to do something semantically different fromstr.append("x")
andpath.concat("x")
to do something semantically the same asstr.append("x")
.Maybe
path
's implicit conversionoperator string_type() const
would cause some variety ofp + q
to become ambiguous. But I've been unable to come up with any such case.
This was entered as a defect against the filesystem library, and because of the interface complexity and the ability to work around by converting to strings and back to paths, it was judged to not be a defect. Read all about it here: https://timsong-cpp.github.io/lwg-issues/2668