Strange and potentially stupid question.
As a mini project, I've been working on creating a Ptr
class to duplicate the mechanism of a pointer - the user should theoretically be able to use this class just like a real pointer without issue and without needing to interact with "actual" C++ pointers (besides some obvious syntax changes). The "memory store" is a very large array of characters. I've managed to implement some version of this to a working prototype, but I've been having a lot of trouble in getting this to be useful in creating a data structure - take, the binary search tree.
Say I have a simplified Ptr
class:
template<typename T>
class Ptr
{
Ptr<T>(){}
T _a_item;
};
and a simplified tree_node
struct:
template <typename T>
struct tree_node
{
T _item;
Ptr<tree_node<T> > _left;
Ptr<tree_node<T> > _right;
};
I'm guessing you immediately spot the glaring problem of the circular dependency, which prevents compilation. Normally, the tree_node
struct would look like:
template <typename T>
struct tree_node
{
T _item;
tree_node<T>* _left;
tree_node<T>* _right;
};
which would be perfectly fine. The problem is that my Ptr
class is not an actual pointer.
I've looked around various forums, and I'm pretty sure what I'm asking for is impossible. But I did want to make sure anyways: is there any way I can make this work without forcing the user to use "real" pointers? I'd also be happy to hear any restructuring tips that could help me make a BST using a self-created Ptr
class.
Edit: Link to exact compilation error: https://godbolt.org/z/rhh15xYK8
Your problem is not circular dependency but the fact that your Ptr
class contains an element instead of a pointer. So your tree_node
needs to contain inside two whole copies of itself! That it is not technically possible.
To make the code make sense and compile you just need to make Ptr
into an actual wrapper of a pointer instead of a wrapper of a copy.
template<typename T>
class Ptr
{
public:
Ptr<T>(){}
T* _a_item;
};
No you cannot sensibly avoid using pointers - nor I see any point in it. You could replace pointers with indices inside a global array - but that would only complicate things. It would be just pointers with extra steps.