Issue with template function
Charles via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Feb 6 09:09:28 PST 2015
I'm trying to create a template function that can take in any
type of array and convert it to a ubyte array. I'm not concerned
with endianness at the moment, but I ran into a roadblock when
trying to do this with strings. It already works with ints,
chars, etc.
Here's the relevant test code:
module byteReader;
public import std.system : Endian;
ubyte[] toBytes(T)(T[] arr)
{
if (arr == null)
{
return null;
}
ubyte[] result = new ubyte[arr.length];
foreach (key, val; arr)
{
result[key] = cast(ubyte) val; // This is line 16
}
return result;
}
string readString(ubyte[] buffer, uint offset, uint length)
{
assert( buffer.length >= offset + length );
char[] chars = new char[length];
foreach(key, val; buffer[offset .. offset + length])
{
chars[key] = cast(char) val;
}
return cast(string)chars;
}
void main() {
import std.stdio;
readString(toBytes!char(['t','e','s','t']),0,4).writeln;
readString(toBytes!string("test"),0,4).writeln; //
This is line 39
}
Here's the output:
byteReader.d(16): Error: cannot cast val of type string to
type ubyte
byteReader.d(39): Error: template instance
byteReader.toBytes!string error instantiating
More information about the Digitalmars-d-learn
mailing list