Interesting GCC extensions
Lutger
lutger.blijdestijn at gmail.com
Mon Sep 28 15:32:10 PDT 2009
Lutger wrote:
> bearophile wrote:
>
>> Lutger:
>>
>>> We don't need an extension for this! Look:
>>>
>>> template Eval(string exp)
>>> {
>>> enum Eval = mixin(exp);
>>> }
>>>
>>> template IsConstant(string exp)
>>> {
>>> enum IsConstant = __traits(compiles, Eval!exp);
>>> }
>>
>>
>> From what I see I think your code is useless for my purposes:
>>
>> // D2 code
>> import std.stdio: writeln;
>>
>> template Eval(string exp) {
>> enum Eval = mixin(exp);
>> }
>>
>> template IsConstant(string exp) {
>> enum IsConstant = __traits(compiles, Eval!exp);
>> }
>>
>> template Tuple(T...) { alias T Tuple; }
>>
>> template Range(int stop) {
>> static if (stop <= 0)
>> alias Tuple!() Range;
>> else
>> alias Tuple!(Range!(stop-1), stop-1) Range;
>> }
>>
>> long ipow(long x, int n) {
>> long result = 1;
>>
>> static if (IsConstant!("n")) {
>> pragma(msg, "constant");
>> static if (n < 5) {
>> foreach (i; Range!(n))
>> result *= x;
>> } else {
>> for (int i; i < n; i++)
>> result *= x;
>> }
>> } else {
>> pragma(msg, "not constant");
>> for (int i; i < n; i++)
>> result *= x;
>> }
>>
>> return result;
>> }
>>
>> enum int w = 5;
>> void main() {
>> int x = 2;
>> const int y = 3;
>> enum int z = 4;
>> writeln(IsConstant!("x"), " ", IsConstant!("y"),
>> " ", IsConstant!("z"), " ", IsConstant!("w"));
>> // prints: false false false true
>>
>> ipow(10, x);
>> ipow(10, y);
>> ipow(10, z);
>> }
>>
>> Even "z" is seen as not constant?
>>
>> Bye,
>> bearophile
>
> They are not compile time constants. Have you tried it with GCC? It gives
> the exact same results.
Actually not for z, I don't know why this doesn't work with dmd. It does say
it is a constant.
More information about the Digitalmars-d
mailing list