Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 778
Aart Stuurman Avatar asked Mar 22 '19 14:03

Aart Stuurman


1 Answers

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
    }
}
like image 135
max66 Avatar answered Oct 26 '22 09:10

max66