Search code examples
c++templatesc++17stdoptional

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.


Solution

  • 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