Home > OS >  Is it possible to have a recursive typedef?
Is it possible to have a recursive typedef?

Time:10-20

The following doesn't work. Is there some way to get around this?

using Node = std::variant<Foo, Bar, std::vector<Node>>;

The error produced is "error: 'Node' was not declared in this scope"

CodePudding user response:

There is a simple reason why such a data structure often cannot exist. You cannot tell the size of it. For all objects the size must be clear already at compile time. But in your case this is not the show stopper. The variant or vector bring their own memory management that makes such things possible.

But the way how the C compiler technically ensures that all sizes are known at compile time is to enforce that all types are properly defined before they are used. Therefore recursive definition like you have in your type are not legal in C .

But there is an exception (in order to allow explicitly things like your type). For structs it possible to have recursive type definition. The reason is that in OOP programming you often need such things (see the discussion here: Linked lists in C )

The solution then looks like this:

struct Node{
   std::variant<Foo, Bar, std::vector<Node>> value;
};

It looks also incorrect. But indeed C accepts it. Node is an incomplete type. For structs this is accepted.

  •  Tags:  
  • c
  • Related