I'm wondering about using the init-statement for if/switch with "placeholders" or anything like that, which are passed to a function as out- or in-out-parameters like e. g. T f(X& x)
.
As an example, the "brand new" C++17 noexcept overloads in std::filesystem
uses an out parameter for passing an std::error_code
by reference:
bool create_directory(const std::filesystem::path& p,
const std::filesystem::path& existing_p,
std::error_code& ec) noexcept;
or
void rename(const std::filesystem::path& old_p,
const std::filesystem::path& new_p,
std::error_code& ec) noexcept;
For a function returning the error code instead of passing it as an out parameter i would write (pseudo code):
namespace fs = std::filesystem;
if (auto ec = fs::rename(old_p, new_p); ec)
{
// use ec handle error
} // ec's lifetime ends
Instead I cannot use it with an init-statement in my if
clause:
namespace fs = std::filesystem;
std::error_code ec;
fs::rename(old_p, new_p, ec);
if (ec)
{
// handle error
}
// ec is still there
Actually I work this around by using a wrapper to hold the caller's code clean:
namespace fs = std::filesystem;
inline std::error_code wrap_rename_ec(const fs::path& old_p,
const fs::path& new_p) noexcept
{
std::error_code ec;
fs::rename(old_p, new_p, ec);
return ec;
}
int main (void)
{
if (auto ec = wrap_rename_ec("old_p", "new_p"); ec)
{
// use ec to handle error
} // ec's lifetime ends
}
I'd find it nice to use something like this (pseudo code):
namespace fs = std::filesystem;
if (std::error_code ec, fs::rename(old_p, new_p, ec); ec)
{
// handle error
} // ec's lifetime ends
I could use the other overload of std::filesystem::rename
which throws an filesystem_error
on error, but passing an existing path or file name as new path or file name does not have to be an error which has to break control flow in the program, I maybe want to append " (2)" or something, because I'm awaiting that case, which is not an exception.
Side note: My question aims not on discussing using exceptions over error codes or vice versa. ;-)
I'm not sure if cases like the one I described above have been taken into account at describing the init-statements for if/switch or have been discarded, while at least for me it would be nice to find a elegant way without wrapper functions handling out/in-out-parameters with init-statements for if/switch.
TL;DR: What is the most elegant way to take profit from init-statements for if/switch in combination with out/in-out parameters? Is it possible at all?
Regards, FA85