type switch

Ali Çehreli via Digitalmars-d digitalmars-d at puremagic.com
Tue May 5 11:12:42 PDT 2015


On 05/04/2015 03:48 PM, Dennis Ritchie wrote:

 > I've been thinking. In D you can write a similar design to the generic
 > functions or somewhere, use static if:
 >
 > // -----
 > static if (is(T == short) || is(T == int) || is(T == long)) {
 >      // do anything
 > } else static if (is(T == real)) {
 >      // ...
 > } else static if (is(T == char)) {
 >      // ...
 > } else static if (is(T == string)) {
 >      // ...
 > } else static if (is(T == int[])) {
 >      // ...
 > } else {
 >      // ...
 > }
 >
 > Why not put in Phobos shorter design type switch:
 >
 > // -----
 > type switch (T) {
 > case short, int, long:
 >      // do anything
 > case real:
 >      // ...
 > case char:
 >      // ...
 > case string:
 >      // ...
 > case int[]:
 >      // ...
 > default:
 >      // ...
 > }
 >
 > This design has been implemented, for example, in Common Lisp (typecase):
 > http://www.lispworks.com/documentation/lw51/CLHS/Body/m_tpcase.htm
 >
 > What do you think about this?

Personally, I haven't felt the need for this becuase usually there is 
something different only for one or two specific types.

I don't see that the syntax becomes shorter to warrant a language 
addition either. (However, the risk of writing 'else if' instead of 
'else static if' is a real annoyance that comes with bad consequences.)

Another option is to use template specializations, which can be mixed-in 
(in bar() below) or called directly (in foo() below):

void doSomethingSpecial(T : int)()
{
     // ...
}

void doSomethingSpecial(T : string)()
{
     // ...
}

void foo(T)()
{
     doSomethingSpecial!T();
}

void bar(T)()
{
     mixin doSomethingSpecial!T;
}

void main()
{
     foo!string();
     bar!int();
}

Ali



More information about the Digitalmars-d mailing list