digitalmars.D.learn - how to find the type of a supplied variable
- seany (19/19) Dec 06 2013 I have the following
- H. S. Teoh (20/42) Dec 06 2013 [...]
- seany (3/3) Dec 06 2013 why do i need the static? (is that not supposed to prevent
- Dicebot (7/10) Dec 06 2013 You can possibly use normal if but most likely you will get
- Jesse Phillips (4/7) Dec 06 2013 'static if' means check this at compile time, which happens to
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?
Dec 06 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
Dec 06 2013
why do i need the static? (is that not supposed to prevent insertations of new scopes inside the braces? is it really needed?)
Dec 06 2013
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.
Dec 06 2013
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.
Dec 06 2013