what was wrong with struct & class in C++?
Russell Lewis
webmaster at villagersonline.com
Wed Dec 26 10:24:30 PST 2007
James Dennett wrote:
>>> ???? I thought that one of the key arguments for putting the syntax
>>> back to the C++ way was that it would make generic code easier to
>>> write. Right now, when we perform an assignment, generic code can't
>>> know (without specialization) whether it is assigning a value or a
>>> reference type.
>> Because if I replace a struct with a class, then I have to go through
>> every use of the struct and add a *.
>
> (snip)
>
> Maybe examples are needed if people are talking past each
> other this obviously?
If Walter will permit me, I will put some words in his mouth. I think
that I understand what Walter is saying, but I disagree with him. :)
Walter has argued that structs should represent value-semantics and
classes should represent reference-semantics. Basically, the idea is
that you can have the code:
Foo thing = <whatever>;
Foo other_thing = thing;
and have it work magically, correctly. For a struct, the assignment
will copy the values from one to the other; for a class, it will copy
only the reference. This is very useful for generic programming because
you can then implement a linked list like this:
struct LinkedList(T) {
T val;
LinkedList!(T) next;
};
The point being that it doesn't matter whether T is a struct or a class,
you will store the "right" think in the linked list node. I see what
he's saying there:
LinkedList!(MyClass) linkedList_with_reference_semantics;
LinkedList!(MyStruct) linkedList_with_value_semantics;
But, IMHO, the definition of "right" thing should be up to the *user* of
the template, not the structure of the language. In my hoped-for-world,
where a class reference needed the little '*' just like a
pointer-to-struct did, we could still use the template above. However,
it would mean that the user of the template would need to use the
template wisely:
LinkedList!(MyClass*) linkedList_with_reference_semantics;
LinkedList!(MyStruct) linkedList_with_value_semantics;
I like the idea that the user of the template gets the power (and
responsibility) to use it wisely.
More importantly to me, I think that the consistency of syntax allows us
to automatically solve any number of other problems. Say that you have
a template which absolutely *must* use reference semantics. In my
hoped-for-world, you could declare a single template:
struct MyRefSemanticsTemplate(T*) {}
But in current D, you have to implement at least 2 different templates,
one for classes, and another for structs. Ick.
Walter, please step in if I have misrepresented your position. Or,
better yet, everybody else please assume that I've misrepresented his
position unless he agrees. :)
More information about the Digitalmars-d
mailing list