Unions and CTFE

Gianni Pisetta via Digitalmars-d digitalmars-d at puremagic.com
Fri Dec 18 06:30:25 PST 2015


Hi all,
i'm coding a parametrized crc implementation that can support 
most of the standards. I want to make it work with CTFE and i 
stumbled upon a difficulty when using 
std.bitmanip.nativeToLittleEndian and 
std.bitmanip.nativeToBigEndian.
The code below is the concept used by EndianSwapper and it does 
not compile because of unions and CTFE. Also as the error message 
is very obscure, is it intended behaviour or a bug?

module testunionctfe;

import std.traits;

auto f(T)(T data) {
   union DataBytes {
     Unqual!T data;
     ubyte[T.sizeof] bytes;
   };

   DataBytes tmp;
   tmp.data = data;
   return tmp.bytes;
}

void main(){
   auto a = f( 0x01020304 );
   enum b = f( 0x01020304 ); //testunionctfe.d(18): Error: 
uninitialized variable 'data' cannot be returned from CTFE
   assert( a == b );
}

If it is intended behaviour, i think i come up with an 
alternative implementation for these two functions with shifts 
and masks to be used only in ctfe(union implementation is faster) 
when the type is uint and ushort(and maybe ulong), that i will 
prepare in a pull request.
Otherwise if it is a bug i will file a bugreport instead.



More information about the Digitalmars-d mailing list