Why D _still_ needs the C preprocessor

Unknown W. Brackets unknown at simplemachines.org
Sun May 6 01:15:50 PDT 2007


Haha, sorry.  It's a shortcut syntax for templates.  Here's a few 
clearer examples:

bool in_array (T) (T item, T[] array);
T max (T) (T[] array);

Essentially, it's like creating a template, with the parameters listed 
after the function first, with a function inside that has the second 
list of parameters and same return type.

I prefer them because it makes namespacing cleaner, usually.  Also, in 
the above examples, you can leave off the ! because it will guess based 
on parameters... meaning you could do:

int[] example;
int i = max(example);

In this case, it does mean that the clause cannot be dynamic, as it can 
in SQL (it must be known at compile time.)  For that, you'd have to 
introduce parameters of some sort, e.g.:

OMF_Record[] select_records (char[] clause) (box[] parameters...);

library.select_records!("rec.record_type == unbox!(int)(parameters[1])")(1);

I'm not sure if the above is exactly right off hand, but you get the 
idea.  That isn't quite as clean (although you could do more advanced 
parsing of the string at compile time to make it better.)

The ! is how you create a template.  In this case, I'm abusing the fact 
that you can leave parens off the function call.

Does that make more sense?

-[Unknown]


> Unknown W. Brackets <unknown at simplemachines.org> spewed this unto the Network: 
>> Hmm.... isn't this what the new mixins are for?
>>
>> Example (just to fit in with your example, you'll have to adjust):
>>
>> ------
>> struct OMF_Record
>> {
>> 	int record_type;
>> }
>>
>> struct library
>> {
>> static:
>> 	OMF_Record[] select_records (char[] clause) ()
>> 	{
>> 		OMF_Record[] results;
>>
>> 		OMF_Record rec;
>> 		if (mixin(clause))
>> 			results ~= rec;
>>
>> 		return results;
>> 	}
>> }
>>
>> int main()
>> {
>> 	OMF_Record[] records = library.select_records!("rec.record_type == 1");
>>
>> 	return 0;
>> }
>> -----
>>
>> That's what you want, right?  I mean, the ! isn't too bad is it?
>>
>> -[Unknown]
> 
> Well, that isn't too bad. But why does it work?  I don't see the word
> "template" anywhere, but at this website:
> 
> 	http://www.digitalmars.com/d/mixin.html
> 
> It never says "mixin" without saying "template" first. I was under
> the impression that mixins only operated on templates.
> 
> I've also never seen the ! away from the word "mixin". What does the
> "!" mean?
> 
> And why does select_records()() get an extra set of parentheses now?


More information about the Digitalmars-d-learn mailing list