简体   繁体   中英

How can I overload the subscript operator to return an optional which can be an lvalue?

I'm learning some C++ features by implementing an octree class. I want the subscript operator on this class to return the octant corresponding to an index . How should I define the subscript operator on the class so that I can both (i) assign to the result and (ii) check if the result is empty or not?

Goal (i) is idiomatically achieved by making the subscript operator return a reference. But references can't refer to nothing, which is a legitimate return value if an octant is empty.

Goal (ii) can be achieved by making the subscript operator return an optional. But then it becomes non-trivial to modify the pointer to the octant – with std::optional<T> , T cannot be a reference.

Here is the broken example (except all instances of optional are prefixed by experimental in the real code because my GCC only has experimental support for C++17).

#include <optional>
#include <iostream>

using namespace std;

class Octree {
    Octree* branch[8];
public:
    Octree();
    ~Octree();
    optional<Octree&> operator[](int index);
};

Octree::Octree() : branch{}
{
}

Octree::~Octree()
{
    for (int i = 0; i < 8; i++) {
        if (branch[i])
            delete branch[i];
    }
}

optional<Octree&> Octree::operator[](int index)
{
    if (branch[index] == NULL)
        return nullopt;
    else
        return &branch[index];
}

int main(int argc, char *argv[])
{
    Octree o;
    if (o[0])
        cout << "Octant o[0] is not empty.\n";
    else
        cout << "Octant o[0] is empty.\n";
    o[0] = new Octree(); // The intent is to modify o
    return 0;
}

The compiler, as expected, colorfully rejects an optional reference.

In file included from parc.cpp:1:0:
/usr/include/c++/6/experimental/optional: In instantiation of ‘class std::experimental::fundamentals_v1::optional<Octree&>’:
parc.cpp:26:61:   required from here
/usr/include/c++/6/experimental/optional:507:7: error: static assertion failed: Invalid instantiation of optional<T>
       static_assert(__and_<__not_<is_same<remove_cv_t<_Tp>, nullopt_t>>,
       ^~~~~~~~~~~~~
/usr/include/c++/6/experimental/optional:713:7: error: forming pointer to reference type ‘Octree&’
       operator->() const
       ^~~~~~~~
/usr/include/c++/6/experimental/optional:723:7: error: forming pointer to reference type ‘Octree&’
       operator->()
       ^~~~~~~~
parc.cpp: In member function ‘std::experimental::fundamentals_v1::optional<Octree&> Octree::operator[](int)’:
parc.cpp:31:10: error: could not convert ‘&((Octree*)this)->Octree::branch[index]’ from ‘Octree**’ to ‘std::experimental::fundamentals_v1::optional<Octree&>’
   return &branch[index];
          ^~~~~~~~~~~~~~
parc.cpp: In function ‘int main(int, char**)’:
parc.cpp:41:24: error: no match for ‘operator=’ (operand types are ‘std::experimental::fundamentals_v1::optional<Octree&>’ and ‘Octree*’)
      o[0] = new Octree();
                        ^
In file included from parc.cpp:1:0:
/usr/include/c++/6/experimental/optional:595:7: note: candidate: std::experimental::fundamentals_v1::optional<_Tp>& std::experimental::fundamentals_v1::optional<_Tp>::operator=(std::experimental::fundamentals_v1::nullopt_t) [with _Tp = Octree&]
       operator=(nullopt_t) noexcept
       ^~~~~~~~
/usr/include/c++/6/experimental/optional:595:7: note:   no known conversion for argument 1 from ‘Octree*’ to ‘std::experimental::fundamentals_v1::nullopt_t’
/usr/include/c++/6/experimental/optional:609:9: note: candidate: template<class _Up> std::enable_if_t<std::__and_<std::__not_<std::is_same<std::experimental::fundamentals_v1::optional<_Tp>, typename std::decay<_Up>::type> >, std::is_constructible<_Tp, _Up>, std::__not_<std::__and_<std::is_scalar<_Tp>, std::is_same<_Tp, typename std::decay<_Up>::type> > >, std::is_assignable<_Tp&, _Up> >::value, std::experimental::fundamentals_v1::optional<_Tp>&> std::experimental::fundamentals_v1::optional<_Tp>::operator=(_Up&&) [with _Up = _Up; _Tp = Octree&]
         operator=(_Up&& __u)
         ^~~~~~~~
/usr/include/c++/6/experimental/optional:609:9: note:   template argument deduction/substitution failed:
/usr/include/c++/6/experimental/optional:628:9: note: candidate: template<class _Up> std::enable_if_t<std::__and_<std::__not_<std::is_same<_T1, _U1> >, std::is_constructible<_Tp, const _Up&>, std::is_assignable<_Tp&, _Up>, std::__not_<std::__or_<std::is_constructible<_Tp, const std::experimental::fundamentals_v1::optional<_Up>&>, std::is_constructible<_Tp, std::experimental::fundamentals_v1::optional<_Up>&>, std::is_constructible<_Tp, const std::experimental::fundamentals_v1::optional<_Up>&&>, std::is_constructible<_Tp, std::experimental::fundamentals_v1::optional<_Up>&&>, std::is_convertible<const std::experimental::fundamentals_v1::optional<_Up>&, _Tp>, std::is_convertible<std::experimental::fundamentals_v1::optional<_Up>&, _Tp>, std::is_convertible<const std::experimental::fundamentals_v1::optional<_Up>&&, _Tp>, std::is_convertible<std::experimental::fundamentals_v1::optional<_Up>&&, _Tp> > >, std::__not_<std::__or_<std::is_assignable<_Tp&, const std::experimental::fundamentals_v1::optional<_Up>&>, std::is_assignable<_Tp&, std::experimental::fundamentals_v1::optional<_Up>&>, std::is_assignable<_Tp&, const std::experimental::fundamentals_v1::optional<_Up>&&>, std::is_assignable<_Tp&, std::experimental::fundamentals_v1::optional<_Up>&&> > > >::value, std::experimental::fundamentals_v1::optional<_Tp>&> std::experimental::fundamentals_v1::optional<_Tp>::operator=(const std::experimental::fundamentals_v1::optional<_Up>&) [with _Up = _Up; _Tp = Octree&]
         operator=(const optional<_Up>& __u)
         ^~~~~~~~
/usr/include/c++/6/experimental/optional:628:9: note:   template argument deduction/substitution failed:
parc.cpp:41:24: note:   mismatched types ‘const std::experimental::fundamentals_v1::optional<_Tp>’ and ‘Octree*’
      o[0] = new Octree();
                        ^
In file included from parc.cpp:1:0:
/usr/include/c++/6/experimental/optional:653:9: note: candidate: template<class _Up> std::enable_if_t<std::__and_<std::__not_<std::is_same<_T1, _U1> >, std::is_constructible<_Tp, _Up>, std::is_assignable<_Tp&, _Up>, std::__not_<std::__or_<std::is_constructible<_Tp, const std::experimental::fundamentals_v1::optional<_Up>&>, std::is_constructible<_Tp, std::experimental::fundamentals_v1::optional<_Up>&>, std::is_constructible<_Tp, const std::experimental::fundamentals_v1::optional<_Up>&&>, std::is_constructible<_Tp, std::experimental::fundamentals_v1::optional<_Up>&&>, std::is_convertible<const std::experimental::fundamentals_v1::optional<_Up>&, _Tp>, std::is_convertible<std::experimental::fundamentals_v1::optional<_Up>&, _Tp>, std::is_convertible<const std::experimental::fundamentals_v1::optional<_Up>&&, _Tp>, std::is_convertible<std::experimental::fundamentals_v1::optional<_Up>&&, _Tp> > >, std::__not_<std::__or_<std::is_assignable<_Tp&, const std::experimental::fundamentals_v1::optional<_Up>&>, std::is_assignable<_Tp&, std::experimental::fundamentals_v1::optional<_Up>&>, std::is_assignable<_Tp&, const std::experimental::fundamentals_v1::optional<_Up>&&>, std::is_assignable<_Tp&, std::experimental::fundamentals_v1::optional<_Up>&&> > > >::value, std::experimental::fundamentals_v1::optional<_Tp>&> std::experimental::fundamentals_v1::optional<_Tp>::operator=(std::experimental::fundamentals_v1::optional<_Up>&&) [with _Up = _Up; _Tp = Octree&]
         operator=(optional<_Up>&& __u)
         ^~~~~~~~
/usr/include/c++/6/experimental/optional:653:9: note:   template argument deduction/substitution failed:
parc.cpp:41:24: note:   mismatched types ‘std::experimental::fundamentals_v1::optional<_Tp>’ and ‘Octree*’
      o[0] = new Octree();
                        ^
In file included from parc.cpp:1:0:
/usr/include/c++/6/experimental/optional:493:11: note: candidate: std::experimental::fundamentals_v1::optional<Octree&>& std::experimental::fundamentals_v1::optional<Octree&>::operator=(const std::experimental::fundamentals_v1::optional<Octree&>&)
     class optional
           ^~~~~~~~
/usr/include/c++/6/experimental/optional:493:11: note:   no known conversion for argument 1 from ‘Octree*’ to ‘const std::experimental::fundamentals_v1::optional<Octree&>&’
/usr/include/c++/6/experimental/optional:493:11: note: candidate: std::experimental::fundamentals_v1::optional<Octree&>& std::experimental::fundamentals_v1::optional<Octree&>::operator=(std::experimental::fundamentals_v1::optional<Octree&>&&)
/usr/include/c++/6/experimental/optional:493:11: note:   no known conversion for argument 1 from ‘Octree*’ to ‘std::experimental::fundamentals_v1::optional<Octree&>&&’
/usr/include/c++/6/experimental/optional: In instantiation of ‘void std::experimental::fundamentals_v1::_Optional_base<_Tp, false>::_M_construct(_Args&& ...) [with _Args = {Octree}; _Tp = Octree&]’:
/usr/include/c++/6/experimental/optional:384:11:   required from ‘std::experimental::fundamentals_v1::_Optional_base<_Tp, false>::_Optional_base(std::experimental::fundamentals_v1::_Optional_base<_Tp, false>&&) [with _Tp = Octree&]’
/usr/include/c++/6/experimental/optional:493:11:   required from here
/usr/include/c++/6/experimental/optional:439:11: error: new cannot be applied to a reference type
           ::new (std::__addressof(this->_M_payload))
           ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
             _Stored_type(std::forward<_Args>(__args)...);
             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

I'm sure there's a way of overloading assignment so that I can return an optional and then assign to it like I do in main above. Thanks for any pointers! ;-)

Goal(i) can be achieved by returning a helper class that overloads the = operator. Goal(ii) can be achieved by returning a helper class that overloads the bool operator.

Consider what happens when your operator[] returns a class that looks like this:

class Octree {

    // Other declarations...

public:

    // Other declarations...

    struct value_at {

        Octree *ptr;

        operator bool() const { return ptr != nullptr; }

        Octree &operator=(const Octree &v)
        {
            return *ptr=v;
        }
    };

    value_at operator[](int index);
};

Constructing the value_at would be your homework assignment; but it's obvious that a returned object with a null ptr represents a nonexistent value, otherwise it points to the value being returned.

Now, your [] operator returns can be used in a boolean context, which evaluates to an indication of whether or not a value was returned, and assigning something to the returned value ends up assigning to the value that [] supposedly returned.

The = operator overload can also check if ptr is null, and throw an exception, as a debugging aid.

The helper class can also declare an operator Octree() const overload, so that the returned object appears to be even more transparent.

Having said all of the above: you could also return a std::optional<std::reference_wrapper<Octree>> which is actually closer aligned to the object described in your question. However using it, in practice, may prove to require some cumbersome syntax (assigning to such std::optional may not necessarily have the effect you're looking for). A simple helper class like this usually leads to a more natural, transparent usage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM