static foreach

bearophile bearophileHUGS at lycos.com
Fri Mar 19 15:54:25 PDT 2010


This can be a small thing for the future.

This is a little example of usage of the "fold" at compile-time in C++ using Boost MPL:
http://www.boost.org/doc/libs/1_42_0/libs/mpl/doc/refmanual/fold.html

typedef vector<long,float,short,double,float,long,long double> types;
typedef fold<
      types
    , int_<0>
    , if_< is_float<_2>,next<_1>,_1 >
    >::type number_of_floats;

BOOST_MPL_ASSERT_RELATION( number_of_floats::value, ==, 4 );


There are several ways to write something like that in D2, I prefer this one, a foreach on types in a templated compile-time function:

int countFloats(Types...)() {
    int tot;
    foreach (T; Types)
        tot += __traits(isFloating, T);
    return tot;
}

static assert(countFloats!(long,float,short,double,float,long,real) == 4);
void main() {}

That's better than the C++ code.
When I've ported my dlibs to D2 I can also use:

alias Tuple!(long,float,short,double,float,long,real) someTypes;
static assert(Filter!(IsFloat, someTypes).length == 4);


In D the "static if", "static assert" can be a little redundant with their non-static variants, but the "static " in front of them is very useful both to ask the compiler a different semantics, and to make the code self-documenting: it's very easy to tell that an if is done at compile-time because there's a "static " before it.

But in D a foreach on a tuple is always static, even in normal functions. In the beginning of my D programming I didn't know this, I have had to look at the asm to know this. So I think it can be better if D2 requires a "static" before "foreach" when the foreach is static, that is done on a tuple. This doesn't change the semantics of the language at all, it's just syntax, it just makes the code more self-documenting (but later if the semantics of tuples changes, becoming more high-level and different, then this can cause a little problem).

(Later, if you want, you can also change the semantics a little, allowing the "static foreach" outside the scope of any function too, like the "static if". The usage of "static foreach(x; 0..10)" is common).

Bye,
bearophile



More information about the Digitalmars-d mailing list