typedef keyword?
Michel Fortin
michel.fortin at michelf.com
Wed Oct 20 18:45:17 PDT 2010
Personally, one thing I've used typedef for is for creating type-safe
bindings for libraries in other languages. For instance, this C/C++
idiom:
typedef struct A A;
essentially creates an undefined type, an opaque type that you can
neither create nor access except through functions that knows about the
definition of struct A. It's more often used with pointers and
functions passed to and from functions:
A *createA();
void cookA(A *a);
void deleteA(A *a);
But because it's declared but undefined. you can't allocate your own
and pretend it's the right thing. This doesn't compile in C/C++:
A *a1 = malloc(sizeof(A));
A *a2 = new A;
This C/C++ code won't compile, and it mustn't because that's an opaque type.
Now, how do you allow the former (functions createA, cookA, deleteA)
while disallowing the later (allocating your own A)? In the past in D I
used typedef to do that.
typedef void A;
typedef void B;
Using typedef instead of alias prevents assignments of one pointer type
to another while giving the desirable properties of an opaque type.
I'm not sure how to do that now without typedef: you can't declare a
struct without defining it in D, so you can't prevent that dummy struct
from being created and allocated and later passed to functions in your
bindings, so there's no hope for make the such binding APIs compatible
with SafeD.
--
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/
More information about the Digitalmars-d
mailing list