New set class

Michiel nomail at please.com
Mon Feb 26 03:49:57 PST 2007


Frits van Bommel wrote:

>>> But if you really want to do put such things in your code you could try
>>> this:
>>> struct Set(T) {
>>>     ...
>>>     void opApplyReverse()() {static assert(0,"don't be silly");}
>>> }
>>>
>>> Since foo is a template member, no attempt is made to compile it unless
>>> it's actually called from somewhere.  If you do try to call it then you
>>> trip the static assert at compile-time.
>>
>> No, if you use a static assert, the compilation will fail as soon as you
>> instantiate the class somewhere. Not if you try to use foreach_reverse.
>> If it weren't a template class, the compiler would throw the error in
>> any case.
> 
> The _member_ is _also_ a template here (with 0 parameters, but a
> template nonetheless). So compilation will only fail if that template is
> instantiated, which will happen only if foreach_reverse is used (or it's
> explicitly called, of course).
> 
> Here, let me show you (some modifications made to above code)
> <SNIP>

Interesting trick. I missed the extra (). One problem, though. If I use
it like this:

foreach_reverse(e ; x) { }

Not specifying the element type (int). I get the "cannot infer type"
error, instead of our custom error message. Why can't the compiler infer
the type? Isn't it right in its face?

> I suspect he may have meant the "void func(T)(T[] name...)" syntax (or
> in this case, "Set!(T) set(T)(T[] elements...)"). That would let the
> user pass as many arguments as he wants, while presenting them as a nice
> typesafe array to the library.

I did try some variations of that. I couldn't make it work quite the way
I wanted.

-- 
Michiel



More information about the Digitalmars-d mailing list