No struct extending?
Stewart Gordon
smjg_1998 at yahoo.com
Fri Sep 8 12:20:29 PDT 2006
Steve Horne wrote:
> In C++, 'struct' is (almost) a synonym for 'class'. More a declaration
> of intent than a different thing. One useful side-effect of this is
> that you can declare structs as extensions of other structs. This can
> be useful even for plain-old-data. e.g. data structures with several
> node types, but some shared fields. Inheritance doesn't always imply
> virtual tables and stuff.
I can imagine that such a feature could be useful indeed. However, the
approach you propose has a caveat.
The problem is that the extending concepts currently in D - class
inheritance, interface implementation and enum base types - satisfy the
"is a" relationship. Basically, given
class Qwert : Yuiop
or
enum Asdfg : int
you can keep any Qwert in a variable of type Yuiop, or any Asdfg in a
variable of type int, without losing any information. This won't be
true of structs if we did what you're suggesting.
Of course, it would at least make sense to somebody coming from a C++
background. But it will be necessary to know whether something's a
struct or a class in order to be sure whether converting it to the base
type would lead to loss of data.
<snip>
> Adding a union...
>
> union u_Variant
> {
> s_Common m_Common;
> s_Branch m_Branch;
> s_Leaf m_Leaf;
> }
>
> just means you have to specify 'm_Branch' or 'm_Leaf' for the
> non-shared fields too.
<snip>
In a union? Doesn't seem to make sense.
But an idea would be to have a means whereby a defined struct can be
used as an anonymous struct. It would also be handy if a struct
instance could be both anonymous and named, if you know what I mean.
But you remind me of an idea I've had for a while, which is being able
to derive a union from a union or struct. This would be used to wrap a
structure from an external API and give it methods or alternative views
of the data.
Stewart.
--
-----BEGIN GEEK CODE BLOCK-----
Version: 3.1
GCS/M d- s:-@ C++@ a->--- UB@ P+ L E@ W++@ N+++ o K-@ w++@ O? M V? PS-
PE- Y? PGP- t- 5? X? R b DI? D G e++++ h-- r-- !y
------END GEEK CODE BLOCK------
My e-mail is valid but not my primary mailbox. Please keep replies on
the 'group where everyone may benefit.
More information about the Digitalmars-d
mailing list