If you have a function that if constexpr ()
decides to do one thing or the other, how to return an lvalue in one case and an rvalue in the other case?
The following example does not compile in the first usage line, because the return type auto
is no reference:
static int number = 15;
template<bool getref>
auto get_number(int sometemporary)
{
if constexpr(getref)
{
return number; // we want to return a reference here
}
else
{
(...) // do some calculations with `sometemporary`
return sometemporary;
}
}
void use()
{
int& ref = get_number<true>(1234);
int noref = get_number<false>(1234);
}
how to return an lvalue in one case and an rvalue in the other case?
I suppose you can try with decltype(auto)
and a couple of parentheses
template<bool getref>
decltype(auto) get_number() // "decltype(auto)" instead of "auto"
{
if constexpr(getref)
{
return (number); // not "number" but "(number)"
}
else
{
return 123123; // just a random number as example
}
}
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