www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Converting a type to a char

reply Thomas Gregory <charles.gregory940 topper.wku.edu> writes:
I would like to check that a char (unknown at compile time) 
matches a particular type but I would like to do so without if 
statements or a hash map as I would like it to be as fast as 
possible.

Ideally I would choose something like this:

enum typeIndex{
byte = 0,
ubyte,
short,
ushort,
int,
uint
}

char[6] typechars="cCsSiI";

bool check(T)(char c){
    return typechars[typeIndex(typeof(T))]==c;
}

Though I know this is implementation is not remotely correct D.
Jan 25
next sibling parent Paul Backus <snarwin gmail.com> writes:
On Friday, 25 January 2019 at 15:53:10 UTC, Thomas Gregory wrote:
 I would like to check that a char (unknown at compile time) 
 matches a particular type but I would like to do so without if 
 statements or a hash map as I would like it to be as fast as 
 possible.

 Ideally I would choose something like this:

 enum typeIndex{
 byte = 0,
 ubyte,
 short,
 ushort,
 int,
 uint
 }

 char[6] typechars="cCsSiI";

 bool check(T)(char c){
    return typechars[typeIndex(typeof(T))]==c;
 }

 Though I know this is implementation is not remotely correct D.
You can do this with AliasSeq and staticIndexOf: import std.meta; alias Types = AliasSeq!(byte, ubyte, short, ushort, int, uint); enum typeIndex(T) = staticIndexOf!(T, Types); char[6] typechars="cCsSiI"; bool check(T)(char c) { return typechars[typeIndex!T] == c; } Runnable version: https://run.dlang.io/is/Tps38K
Jan 25
prev sibling parent Murilo <murilomiranda92 hotmail.com> writes:
On Friday, 25 January 2019 at 15:53:10 UTC, Thomas Gregory wrote:
 I would like to check that a char (unknown at compile time) 
 matches a particular type but I would like to do so without if 
 statements or a hash map as I would like it to be as fast as 
 possible.

 Ideally I would choose something like this:

 enum typeIndex{
 byte = 0,
 ubyte,
 short,
 ushort,
 int,
 uint
 }

 char[6] typechars="cCsSiI";

 bool check(T)(char c){
    return typechars[typeIndex(typeof(T))]==c;
 }

 Though I know this is implementation is not remotely correct D.
Join this group https://www.facebook.com/groups/662119670846705/ , it is the D lang facebook group, there we can help you out with any doubts.
Feb 05