operator new(): struct v. class
Kirk McDonald
kirklin.mcdonald at gmail.com
Mon Aug 20 13:27:35 PDT 2007
C. Dunn wrote:
> Kirk McDonald Wrote:
>
>
>>>But Walter, how did you handle operator new()? It needs to be agnostic about class/struct.
>>>
>>>class C{int x;};
>>>stuct S{int x;};
>>>typedef C MyType;
>>>//typedef S* MyType;
>>>MyType inst = new MyType;
>>>
>>>If you use the second typedef, this will not compile! That is the problem.
>>>
>>>Why not provide an operator New() which expects a pointer type when used for structs? Just have the compiler translate it. I cannot see how to write such a generic operator New() myself.
>>>
>>
>>It's a trivial bit of template code. Something like this:
>>
>>T New(T)() {
>> static if (is(T U == U*)) {
>> return new U;
>> } else {
>> return new T;
>> }
>>}
>>
>>class C {}
>>struct S {}
>>
>>void main() {
>> C c = New!(C);
>> S* s = New!(S*);
>>}
>
>
> I don't understand your static if expression. Where in the docs is there an explanation for "is(T U == U*)"? I completely missed that, and I really do not understand what it does.
>
It's the IsExpression:
http://www.digitalmars.com/d/expression.html#IsExpression
Specifically, it's this form of the IsExpression:
is ( Type Identifier == TypeSpecialization )
"The condition is satisfied if Type is semantically correct and is the
same as TypeSpecialization. The Identifier is declared to be either an
alias of the TypeSpecialization or, if TypeSpecialization is dependent
on Identifier, the deduced type."
That is, if T can be expressed as U*, is() evaluates to true, and U is
declared to be an alias to the appropriate type.
>
>>Handling constructor arguments, too, is only a little more complicated.
>
>
> Someone who can figure it out does not need to.
I don't understand what you mean by this.
> I think that's why people are ignoring my concern. It's disregard for the novice.
>
> If y'all want C++ programmers to adopt D, you have to make it easy. C++ is entrenched. This operator new() issue and the lack of a stack trace from an exception thrown during contract-checking weaken the arguments for adoption. Maybe someday these will be addressed. D certainly has potential.
>
> And yes, before anybody mentions it, flectioned is really cool. If it gets integrated into tango, and if tango is released for D 2.0, then the stack-trace issue might disappear. Then maybe tango will provide an operator New().
The above is quite easy... assuming you know about the appropriate
tools. The IsExpression is one of D's most powerful compile-time tools.
If you're doing any generic programming in D, it is one of the first
things you should learn about.
--
Kirk McDonald
http://kirkmcdonald.blogspot.com
Pyd: Connecting D and Python
http://pyd.dsource.org
More information about the Digitalmars-d
mailing list