Search code examples
c++c++17constexprautoif-constexpr

How to decide constexpr to return a reference or not


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);
}

Solution

  • 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
        }
    }