Template question
Daniel Keep
daniel.keep.lists at gmail.com
Thu Feb 22 14:51:04 PST 2007
Michiel wrote:
> I'm not yet familiar enough with the template system to do this.
>
> I wrote the following function:
>
> ----------------------------------------
> Set!(T[0]) set(T ...)(T elements) {
> auto result = new Set!(T[0]);
>
> foreach (element; elements) {
> result.add(element);
> }
>
> return result;
> }
> ----------------------------------------
>
> This gives a nice set literal syntax with implicit type deduction.
>
> auto x = set(4, 5, 6, 99);
>
> But the user of the function should also have the option to use it like
> this:
>
> auto x = set!(int);
>
> To create the empty set (that can hold int). How can I implement this?
>
> Thanks!
SetOf!(T) set(T...)(T elements)
{
auto result = new SetOf!(T);
foreach( element ; elements )
result.add(element);
return result;
}
template SetOf(T...)
{
static if( is( typeof(T[0]) ) )
alias Set!(typeof(T[0])) SetOf;
else
alias Set!(T[0]) SetOf;
}
Obviously, this only works if Set!(T) expects "T" to be an actual type.
Note that I haven't tried the above. This should *theoretically* work
since taking the type of a type makes no sense (hence, the is expression
should fail), whilst taking the type of a value does.
If it doesn't work, blame it on just having woken up :P
> PS: I would have liked to skip the type altogether for the empty set,
> but the problem appears when you want to put something inside that set.
> I've considered using a dummy type and to somehow construct the correct
> set-type after the first insert, but it wouldn't be consistent with
> normal sets and altogether too much trouble.
Bad idea; the more you can get fixed at compile-time, the better. For
instance, std.boxer.Box can store any type you want. Putting things
into a box is easy enough,
auto x = box(42);
But taking them back out is a bit ugly.
auto y = unbox!(int)(x);
The reason for this is that the compiler needs to know what the result
type of "unbox" is at compile-time, so you need to tell it.
-- Daniel
--
Unlike Knuth, I have neither proven or tried the above; it may not even
make sense.
v2sw5+8Yhw5ln4+5pr6OFPma8u6+7Lw4Tm6+7l6+7D
i28a2Xs3MSr2e4/6+7t4TNSMb6HTOp5en5g6RAHCP http://hackerkey.com/
More information about the Digitalmars-d
mailing list