void pointer syntax
Ali Çehreli
acehreli at yahoo.com
Tue May 15 19:30:47 PDT 2012
On 05/15/2012 07:01 PM, Stephen Jones wrote:
> Using Object gives exactly the same problem as the Object super class
> does not have vcount variable.
But Object is better than void* because the latter has no safety and
completely unusable. All you can do with a void* is to cast it back to
its own type. If you don't keep type information somehow, nobody knows
what the original type was.
> Casting is not a solution
That is the only solution. It may be somehow wrapped, but you must cast
void* to a useful type first.
> because the
> reason for throwing different sorts of widgets into a single array was
> so I did not have to track what each type of object was;
Yeah, great! That's polymorphism. Great. You keep a Widget[] and use it.
> not tracking
> what each object in the array is I have no means of knowing what to cast
> each Widget in the array to.
Exactly! :) Either you or the compiler must keep track of it. void*
removes any trace of type information.
> If some one knows void pointer syntax that would be helpful.
import std.stdio;
void main()
{
int i;
double d;
void*[] array;
array ~= cast(void*)&i;
array ~= cast(void*)&d;
foreach (address; array) {
writeln("I don't know what type of object is at ", address);
}
}
> As I
> understand it there is a type called size_t that takes the address of as
> a a value.
No. size_t is suitable to represent concepts like size, quantity, etc.
Concepts that are supposed to be never less than zero.
> Can I make an array of these and simply initialize each with
> &button1, &cursor, etc? Also, how is size_t freed?
You can but it would make no sense:
import std.stdio;
void main()
{
int i;
double d;
size_t[] array;
array ~= cast(size_t)&i;
array ~= cast(size_t)&d;
foreach (size; array) {
writeln("I don't know what to do with this amount: ", size);
}
}
Getting back to your original question, here is another solution where
Widget is a class (not an interface) that has a vertCount member. It
makes it necessary that the subclasses construct it with that information:
import std.stdio;
class Widget{
abstract void draw();
size_t vertCount;
this(size_t vertCount)
{
this.vertCount = vertCount;
}
}
class Button : Widget{
override void draw(){}
this()
{
super(100);
}
}
class Cursor : Widget{
override void draw(){}
this()
{
super(200);
}
}
void main()
{
Widget[] widgets;
widgets~=new Button();
widgets~=new Cursor();
foreach(Widget w; widgets){
writeln(w.vertCount);
}
}
Ali
--
D Programming Language Tutorial: http://ddili.org/ders/d.en/index.html
More information about the Digitalmars-d-learn
mailing list