Run-time initialised static variables

dekevin dekeyser.kevin97 at gmail.com
Wed Feb 7 20:22:20 UTC 2018


On Wednesday, 7 February 2018 at 20:10:10 UTC, dekevin wrote:
> On Wednesday, 7 February 2018 at 16:26:16 UTC, Dominikus Dittes 
> Scherkl wrote:
>> On Wednesday, 7 February 2018 at 12:10:38 UTC, dekevin wrote:
>>
>>
>>> struct ℚ{
>>>      ℤ num, den; //cannot call constructors on these, since 
>>> they require gmp_init, which requires runtime code
>>>      //Default initialiser disabled, since else num=0,den=0
>>
>> You can use a different default initializer:
>>       ℤ num = 0, den = 1;
>>
>> Thus avoiding the bad denominator.
>
> I appreciate the help, but I cannot instantiate these variables 
> with a constructor.
> Whenever I do, the compiler tries to figure out its values at 
> compile-time.
> This it cannot do however, since the code requires gmp_init for 
> constructing an explicit value, which is only available after 
> dynamically linking GMP.
>
> Here is the error I get:
>      source/gmp/z.d(117): Error: __gmpz_init_set_si cannot be 
> interpreted at compile time, because it has no available source 
> code
>      source/util.d(575):        called from here: 
> _MpZ(__mpz_struct(0, 0, null)).this(0)
>      source/gmp/z.d(117): Error: __gmpz_init_set_si cannot be 
> interpreted at compile time, because it has no available source 
> code
>      source/util.d(575):        called from here: 
> _MpZ(__mpz_struct(0, 0, null)).this(1)
>
> I don't really know what to do now, since I have another struct 
> which already uses static variables with the same naming 
> convention and I'll also need it a second time when I write the 
> bindings to MPFR.

I should perhaps add how  ℤ looks like.
Here is a stripped-down version:

struct ℤ {
     @disable this();
     this(T)(T value) @trusted
         if (isArithmetic!T)
     {
         version(ccc) { ++_ccc; }
         static      if (isUnsigned!T)
             __gmpz_init_set_ui(_ptr, value);
         else static if (isFloating!T)
             __gmpz_init_set_d(_ptr, value);
         else                    // isSigned integral
             __gmpz_init_set_si(_ptr, value);
     }

~this() @trusted
     {
         assert(_ptr, "Pointer is null");
         //if(hasBeenInit)
         __gmpz_clear(_ptr); version(ccc) { ++_ccc; }

     }

     inout(__mpz_struct)* _ptr() inout return @system
     {
         return &_z;
     }
}


More information about the Digitalmars-d-learn mailing list