2

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.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
Mutating Algorithm
  • 2,604
  • 2
  • 29
  • 66
  • @NicolBolas Not necessarily. An empty array for example. data[0] will not (should not) be a valid reference to return. I'm doing this more as a C++ technical exercise rather than thinking about the practicality of the situation. – Mutating Algorithm Apr 08 '20 at 02:27
  • 6
    An "optional" `std::reference_wrapper` is logically equivalent to a pointer. Null pointer? No soup for you! A non-null pointer? Here's your object. The End. "The more you overthink the plumbing, the easier it is to stop up the drain" -- Scotty, Star Trek III. – Sam Varshavchik Apr 08 '20 at 02:31
  • 2
    Why not just return `const T*`? If it is `nullptr` then there is no data. This is how people normally do it. – ALX23z Apr 08 '20 at 02:32
  • @ALX23z this is more of a C++ technical question than finding alternative (better) ways to do this. – Mutating Algorithm Apr 08 '20 at 02:36
  • The answer is: `std::optional` is designed for a purpose. What you ask is not what `std::optional` is designed for. Raw pointer is used for that. At most consider `observer_ptr`. – ALX23z Apr 08 '20 at 02:39

1 Answers1

4

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

Jarod42
  • 203,559
  • 14
  • 181
  • 302