Vector Swizzling in D

Don Clugston dac at nospam.com
Thu Mar 15 02:30:25 PDT 2012


On 14/03/12 18:46, Boscop wrote:
> On Wednesday, 14 March 2012 at 17:35:06 UTC, Don Clugston wrote:
>> In the last bit of code, why not use CTFE for valid(string s) instead
>> of templates?
>>
>> bool valid(string s)
>> {
>> foreach(c; s)
>> {
>> if (c < 'w' || c > 'z') return false;
>> }
>> return true;
>> }
>>
>> In fact you can use CTFE for the other template functions as well.
>
> In the original version I actually did this, but even with -O -inline
> -release the opDispatchs call didn't get inlined. I thought it was
> caused by CTFE-code that prevented the inlining.
> FWIW, this was the original code using CTFE:
> ---
> import std.algorithm: reduce;
> struct Vec {
> double[4] v;
> @property auto X() {return v[0];}
> @property auto Y() {return v[1];}
> @property auto Z() {return v[2];}
> @property auto W() {return v[3];}
> this(double x, double y, double z, double w) {v = [x,y,z,w];}
> @property auto opDispatch(string s)() if(s.length <= 4 &&
> reduce!((s,c)=>s && 'w' <= c && c <= 'z')(true, s)) {
> char[] p = s.dup;

This won't be CTFEd, because it's not forced to be a compile-time constant.

> foreach(i; s.length .. 4) p ~= p[$-1];
This too.

But, you can do something like:
enum p = extend(s);
since p is an enum, it must use CTFE.

> int i(char c) {return [3,0,1,2][c-'w'];}
this isn't forced to be CTFE either.

> return Vec(v[i(p[0])], v[i(p[1])], v[i(p[2])], v[i(p[3])]);
> }

> ---
> (I was using reduce here only to demonstrate D's functional features and
> nice lambda syntax. Maybe that's what prevented inlining?)



More information about the Digitalmars-d-learn mailing list