I'd like to run some functions in sequence, short-circuiting when one of them succeeds. They all have the same return type, are mostly zero argument callables (lambdas with captures). To identify success, the function returns non-empty optional. The thing is that sometimes those functions return references, in which case writing
return std::optional{some_reference};
will be UB. But, it seems like doing
return std::optional{std::ref(some_reference)} ;
is not. GCC 9 happily compiles that. Though clang 7 doesn't.
#include <optional>
#include <functional>
#include <iostream>
int main()
{
int x = 12;
auto job = [](const int& y)
{
return std::optional{std::ref(y)};
};
auto value = job(x);
x = 25;
std::cout << *value << '\n';
}
Which one of them is right?
I believe the code should compile, because class template argument deduction should be applied and std::reference_wrapper<int> deduced.
The code in OP is well-formed and should yield an optional<reference_wrapper<int>>.
This is llvm bug 34650. A simpler example demonstrating the problem is:
std::optional o(42);
gcc allows it (with o being a std::optional<int>), clang does not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With