Is there any better solution?
No, the solution that you showed is the best (and the only) one. union
s are pretty simplistic - they do not "track" what you've assigned to what. All they do is let you reuse the same memory range for all their members. They do not provide anything else beyond that, so enclosing them in a struct
and using a "type" field for tracking is precisely the correct thing to do.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…