alias = compile-time variants?

Jason Spencer spencer8 at sbcglobal.net
Sat Jul 31 02:24:55 PDT 2010


== Quote from Philippe Sigaud (philippe.sigaud at gmail.com)'s article
> --0016e6d58a039d35e2048c9aa7e2
>
> I thought they could only be symbols. That is, an alias is a 'link',
a sort
> of pointer to a symbol: a template name, a module name, a function
> name, etc.

Whatever confidence you inspired by removing type from the list is
quickly lost and more when you add module name--I hadn't thought of
that! :)


> Wisdom, I don't know, as I still feel like I'm exploring things. But
> template constraints are there to limit what you can instantiate.
> ...
> Say I have a template that takes an alias, fun, and a type, T.
> fun is supposed to be a function, but in fact why limit it to that?
> What I need is for foo to be callable with a T. So let's test for
> that:
> auto doSomething(alias fun, T)(T t)
> if (is(typeof( fun(T.init) )))
> {
> // now that I'm here, I can freely use fun as a callable on any T
>  auto result = fun(t);
> // ...
> }

I understand this example, and (most of) the mechanics of constraints.
What I'm not so sure about is the recommended practice around their
use.  I see lot's of code that doesn't check those things.  Suppose
you left off the constraint and did:

class Foo(U){}
doSomething!(Foo, int)(3)

it seems like there's a good chance you could get:

auto result = Foo!(int);  // type inferred from 3

(since this doesn't actually work like I'm saying, please conveniently
imagine a similar case that does. :)

Even with your constraint, I'm not sure I feel any more comfortable.
If it compiles in the body of doSomething, it will compile in the
constraint--not sure I've added any value.

So how do you sleep at night not knowing if there's some funky syntax
on somebody's template-that-takes-a-template which, when combined with
some inference, might look like your function call on a value param?
My initial reaction is to specify the hell out of the constraints, but
I couldn't beat the feeling I was going overboard.  I suspect that
most people rely on the fact that most improper calls won't compile.
Maybe I'm still too new to the syntax to have a good feel for what
will get caught, and what could interpreted by the compiler in
multiple ways depending on the actual arguments.

So, do folks write constraints to ensure that modules don't get passed
to their templates?  :)

Jason


More information about the Digitalmars-d-learn mailing list