recursive template (first attempt)
    akcom 
    CppCoder at gmail.com
       
    Wed Apr 19 20:25:55 PDT 2006
    
    
  
I apologize if this is an easily resolved problem, this is my first
attempt at writing a template function.  the objective of this function
is to mimic the behavior of the AP hash function, but as a template
function obviously.  Here is what I have so far:
uint aphash( ubyte []buf )
{
	uint hash;
	
	for ( uint i = 0; i < buf.length; i++ )
	{
		hash ^= ((i & 1) == 0) ?	(  (hash <<  7) ^ (buf[i]) ^ (hash >> 3)) :
									(~((hash << 11) ^ (buf[i]) ^ (hash >> 5)));
	}
	return hash;
}
template aphasht( T : ubyte [] )
{
	uint aphasht( T t )
	{
		uint result;
		static if ( t.length == 0 )
		{
			return 0;
		}
		static if ( t.length & 1 )
		{
			result = aphasht( t[1..$] );
			return (result << 7) ^ t[0] ^ (result >> 3);
		}
		else
		{
			result = aphasht( t[1..$] );
			return (result << 11) ^ t[0] ^ (result >> 5);
		}
	}
}
void test()
{
	static ubyte []str = [ 0x01, 0x02, 0x03, 0x03 ];
	writefln( "aphash(str) = %X", aphash( str ) );
	writefln( "aphasht(str) = %X", aphasht!(ubyte [])( str ) );
}
When I attempt to compile it, I get the following errors:
dmd -w -c main.d
main.d(49): expression ((t).length) == 0u does not evaluate to a boolean
main.d(53): expression ((t).length) & 1u does not evaluate to a boolean
main.d(70): template instance main.aphasht!(ubyte[]) error instantiating
Could someone please point out my mistake, and if there is a more
elegant way of completing this task, I'd appreciate some input on that
as well.
Regards,
Alex
    
    
More information about the Digitalmars-d-learn
mailing list