Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return an optional pointer or reference ( std::optional )?

Suppose I have the following template function:

template <typename T>
std::optional<std::reference_wrapper<const T>> larger(const T data[], size_t count) {
    if(!count) return std::nullopt;

    size_t index_max {};
    for(size_t i {1ULL}; i < count; ++i)
        index_max = data[i] > data[index_max] ? i : index_max;

    return std::optional< std::reference_wrapper<const T> > {&data[index_max]};
}

What i'm trying to do is to return an optional reference but not succeeding in doing so. I'm not sure how to proceed from here. This is what I came up with, initially what I had was std::optional<const T*> as the return type.

like image 458
Mutating Algorithm Avatar asked Oct 22 '25 03:10

Mutating Algorithm


1 Answers

You have a "typo", it should be (without &):

return std::optional< std::reference_wrapper<const T> > {data[index_max]};

Demo

Alternatively, as you specify return type (for optional), you might use std::cref:

return std::cref(data[index_max]);

Demo

like image 80
Jarod42 Avatar answered Oct 24 '25 19:10

Jarod42



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!