how to find the type of a supplied variable
H. S. Teoh
hsteoh at quickfur.ath.cx
Fri Dec 6 12:37:23 PST 2013
On Fri, Dec 06, 2013 at 09:18:51PM +0100, seany wrote:
> I have the following
>
> void functionName(T)(T argumentVar)
> {
>
> /+
> now i want that based on type of argumentVar, things will be
> done
> eg :
> if there is a function gettype; then :
> +/
>
> switch(argumentVar.gettype)
> {
> case "string array":
> //do something
> case "string":
> //treat srting as a file...
> //then do some other things
> }
>
> }
[...]
Use static if and an is-expression:
static if (is(T == string[]))
// handle string arrays
else static if (is(T == string))
// handle strings
else static assert(0); // this is a good idea to catch bugs,
// if somebody passes in a type that
// isn't supported
Depending on your application, you may want to use the more permissive
is(X : Y) syntax instead. The ':' means "if X can implicitly convert to
Y", whereas the is(X == Y) syntax means "if X is exactly the same type
as Y". So if you want to accept both string and char[], you'd write:
static if (is(T : const(char)[]))
// handles string, char[], and const(char)[]
since both unqualified and immutable can implicitly convert to const.
T
--
Unix is my IDE. -- Justin Whear
More information about the Digitalmars-d-learn
mailing list