When writing a function with auto
return type we can use constexpr if
to return different types.
auto myfunc()
{
constexpr if (someBool)
{
type1 first = something;
return first;
}
else
{
type2 second = somethingElse;
return second;
}
}
However, I'm struggling to work out how to make just one of the types a reference. It seems like the following code still returns an r-value for both branches
auto myfunc()
{
constexpr if (someBool)
{
type1 &first = refToSomething;
return first;
}
else
{
type2 second = somethingElse;
return second;
}
}
Is there a way to do this? Google isn't revealing much as there are so many tutorials on more general use of auto and return by reference. In my particular case the function is a class method and I want to either return a reference to member variable or a view of an array.
Just auto
will never be a reference. You need decltype(auto)
instead, and also put the return value inside parentheses:
decltype(auto) myfunc()
{
if constexpr (someBool)
{
type1 &first = refToSomething;
return (first);
}
else
{
type2 second = somethingElse;
return second;
}
}