4

我通过实现一个八叉树类来学习一些 C++ 特性。我希望此类上的下标运算符返回与index 对应的八分圆。我应该如何在类上定义下标运算符,以便我可以(i)分配给结果和(ii)检查结果是否为空?

目标 (i) 习惯上通过使下标运算符返回一个引用来实现。但是引用不能引用任何内容,如果八分圆为空,这是一个合法的返回值。

目标 (ii) 可以通过使下标运算符返回一个可选项来实现。但是,修改指向八分圆的指针变得不简单——用std::optional<T>,T不能是引用。

这是损坏的示例(除了在实际代码中的所有实例optional都带有前缀,experimental因为我的 GCC 仅对 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;
}

正如预期的那样,编译器以丰富多彩的方式拒绝可选引用。

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 ‘&amp;((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)...);
             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

我确信有一种方法可以重载赋值,这样我就可以返回一个可选的,然后像main上面那样分配给它。感谢您的任何指点!;-)

4

1 回答 1

2

可以通过返回一个重载=运算符的辅助类来实现目标(i)。目标(ii)可以通过返回一个重载bool操作符的辅助类来实现。

考虑当您operator[]返回一个如下所示的类时会发生什么:

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);
};

构建value_at将是您的家庭作业;但是很明显,返回的对象为nullptr表示不存在的值,否则它指向正在返回的值。

现在,您的[]运算符返回可以在布尔上下文中使用,它评估是否返回值的指示,并且将某些内容分配给返回的值最终分配给[]应该返回的值。

=运算符重载还可以检查是否为空ptr,并抛出异常,作为调试辅助。

辅助类也可以声明一个operator Octree() const重载,这样返回的对象就显得更加透明了。

说了以上所有内容:您还可以返回std::optional<std::reference_wrapper<Octree>>实际上与您的问题中描述的对象更接近的 a 。然而,在实践中使用它可能需要一些繁琐的语法(分配给这样std::optional的可能不一定有你正在寻找的效果)。像这样的简单助手类通常会导致更自然、更透明的用法。

于 2019-06-14T01:52:11.980 回答