how to find the type of a supplied variable

2013-12-06 Thread seany

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
}

}


How do I incorporrate this?


Re: how to find the type of a supplied variable

2013-12-06 Thread H. S. Teoh
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


Re: how to find the type of a supplied variable

2013-12-06 Thread seany
why do i need the static? (is that not supposed to prevent 
insertations of new scopes inside the braces? is it really 
needed?)


Re: how to find the type of a supplied variable

2013-12-06 Thread Dicebot

On Friday, 6 December 2013 at 20:58:15 UTC, seany wrote:
why do i need the static? (is that not supposed to prevent 
insertations of new scopes inside the braces? is it really 
needed?)


You can possibly use normal if but most likely you will get 
compilation errors from other conditional branches as they will 
use parameter type in semantically incorrect way. `static if` 
avoids compilation of not matching blocks and does not have this 
issue. You can explicitly define new scope using one extra pair 
of braces if you want it.


Re: how to find the type of a supplied variable

2013-12-06 Thread Jesse Phillips

On Friday, 6 December 2013 at 20:58:15 UTC, seany wrote:
why do i need the static? (is that not supposed to prevent 
insertations of new scopes inside the braces? is it really 
needed?)


'static if' means check this at compile time, which happens to 
not introduce a new scope, because otherwise it wouldn't be very 
useful.