New operators opStaticIndex and friends

H. S. Teoh hsteoh at quickfur.ath.cx
Tue May 14 23:54:56 UTC 2019


On Tue, May 14, 2019 at 08:07:03PM +0000, Ahmet Sait via Digitalmars-d wrote:
[...]
> I've read it before, and read it again now just to be sure. Obviously
> such functions (the ones that check whether a variable is known at CT)
> need to be templates and get instantiated on every call to actually
> work.

Templates are not instantiated once per call.  They are only
instantiated once per unique combination of argument types.


> Something close to this:
> 
> auto opIndex()(size_t i)

This doesn't work, as the compiler sees `i` as a runtime parameter. When
compiling this code, the compiler doesn't know (nor care) where the
argument might have come from. It can't, because this function could
potentially be called from an external module separately compiled, or
even bound only at runtime via a dynamic library load.

Also, since the template parameter list is empty, this template will
only be instantiated once throughout the entire program. So the static
if below won't work as you want it to.


> {
>     enum types = [ "double", "long", "int" ];
>     static if (__traits(isKnownAtCT, i))
>     {
>         static if (i < types.length)
>             return mixin("cast(" ~ types[i] ~ ")i");
>         else
>             return "Here be dragons";
>     }
> }

Something closer to what you're looking for might be this:

	auto opIndex(alias i)() if (is(typeof(i) == size_t) {
		...
	}

This will get instantiated once per call, but will require !() syntax
rather than the usual, so the way the [] operator is overloaded will
have to be extended.  Also, `i` in this scope will refer to the actual
variable in the caller's scope, so if the function body modifies it you
could get very strange results.

And I"m not 100% sure this will work for all possible argument types;
the alias parameter may not accept arbitrary expressions due to various
limitations, so you might end up with the strange situation that
opIndex!0 works but opIndex!(1-1) doesn't.


T

-- 
English is useful because it is a mess. Since English is a mess, it maps well onto the problem space, which is also a mess, which we call reality. Similarly, Perl was designed to be a mess, though in the nicest of all possible ways. -- Larry Wall


More information about the Digitalmars-d mailing list