问题
When I compile a binary tree containing optional types:
#include <optional>
class BinaryTree
{
public:
BinaryTree();
int value;
std::optional<BinaryTree> left,right;
};
int main()
{
return 0;
}
via
g++ -std=c++17 -Wfatal-errors main.cpp
I face with this error
In file included from /usr/include/c++/7/bits/move.h:54:0,
from /usr/include/c++/7/bits/stl_pair.h:59,
from /usr/include/c++/7/utility:70,
from /usr/include/c++/7/optional:36,
from main.cpp:1:
/usr/include/c++/7/type_traits: In instantiation of ‘struct std::is_trivially_copy_constructible<BinaryTree>’:
/usr/include/c++/7/optional:103:8: required from ‘class std::_Optional_base<BinaryTree>’
/usr/include/c++/7/optional:451:11: required from ‘class std::optional<BinaryTree>’
main.cpp:8:28: required from here
/usr/include/c++/7/type_traits:1409:12: error: invalid use of incomplete type ‘class BinaryTree’
struct is_trivially_copy_constructible
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
compilation terminated due to -Wfatal-errors.
How should I fix this error?
回答1:
Optional contains the complete instance of the type when it is engaged.
Storing two instances of a type within an instance of the type is impossible; it requires 2<=1.
Consider using a unique pointer to the type instead of an optional.
If you want to be able to copy the tree then you have to write a value pointer. Value pointer is a pointer that knows how to deep copy itself.
回答2:
@Yakk's answer is correct.
As @Dietmar Kühl points out, std::unique_ptr
is what you want for nullable not-in-place storage:
#include <memory>
class BinaryTree
{
public:
BinaryTree();
int value;
std::unique_ptr<BinaryTree> left,right;
};
int main()
{
return 0;
}
回答3:
You want to use a BinaryTree pointer instead of actual BinaryTree member, because the type is incomplete. Replace
std::optional<BinaryTree> left,right;
with
std::optional<BinaryTree*> left,right;
来源:https://stackoverflow.com/questions/48604266/c17-optional-tree-error-invalid-use-of-incomplete-type