Search code examples
aliasdtypedefinitializer

How can I use std.typecons.Typedef with functions?


I have:

typedef void function(int) handler = &noOp;

As typedef is deprecated, I'm told to use either alias (which doesn't allow to set a default initializer) or std.typecons.Typedef (which does). However, the following doesn't work:

import std.typecons;
alias handler = Typedef!(void function(int), &noOp);

How can I set a function type's initializer without typedef?


Solution

  • This is a good example of a time to know the basics - I think understanding the ins and outs of struct is more helpful than Typedef since you can do so much more with it. Here's how you can do this:

    void noOp(int) {} 
    struct handler { 
        void function(int) fn = &noOp;  // here's the initializer
        alias fn this;  // this allows implicit conversion
    } 
    void main() { 
        handler h; 
        assert(h == &noOp); // it was initialized automatically!
        static void other(int) {} 
        h = &other; // and you can still reassign it
    } 
    

    The alias this is perhaps controversial - it allows implicit conversion to and from the base type, like alias, but this is different than typedef. You could also customize this by doing individual constructors, opAssign overloads, etc., depending on the exact behavior you need. Ask me and I can clarify, but also you will want to play with it and see if you like how it works now.