declaration with typedef

Stanislav Blinov stanislav.blinov at gmail.com
Mon Dec 27 17:09:19 PST 2010


On 12/27/2010 06:41 PM, Hamad Mohammad wrote:
>> If you tried to assign person2 to person1 or vice versa
>
> how?
>

I don't think I got what David meant with it either. Assigning instances 
of the same type is perfectly valid as long as you do not define some 
very peculiar opAssign.

Andrej, on the other hand, made a perfect point.
A typedef is deprecated in D2. typedef in D2 differs from C/C++ one. 
What typedef does (in the old, D1 way) is introducing a new, distinct 
type. Many D constructs, especially templates, can handle only certain 
types. Those, depending on conditions, may or may not include 
user-defined types.

writeln requires that a given value is 'formattable' to string. It knows 
how to deal with numerics, strings, arrays, structs and classes. But it 
does not put out assumptions on unknown types (and typedef'd type is 
"unknown" to D's type system). There are some ways to "introduce" your 
types to certain constructs. For example, if you do
writeln(person1) in your code, you'll get "Human" on the console - this 
is a default way writeln handles structs. But if you define a method 
"toString" for your Human struct, e.g:

import std.conv;

struct Human
{
	//...
	string toString()
	{
		return text(name, ": ", age);
	}
}

, then writeln(person1) would output 'aaaa: 12' to the console.
(Mind that this 'toString' idiom may change, which is the effect of 
recent discussions about this certain topic).

Generally, if you want a "distinct" type in D2, define a struct (or a 
class if you want your type to have reference semantics). If you want a 
simple alias to existing type, use "alias" declaration (alias is an 
analog of C/C++ typedef, though the keyword itself does more than this. 
You can find out additional uses in documentaion or "The D Programming 
Language" book).

At this point, language gurus should start throwing rotten tomatoes at 
my general location, but I tried to explain the thing in the easiest way 
I could.


More information about the Digitalmars-d-learn mailing list