Storing templates

Bill Baxter dnewsgroup at billbaxter.com
Fri Mar 9 11:07:55 PST 2007


Simen wrote:
> Hi.
> 
> I'm new to D, and I'm having a little problems using templates for my parser project...
> 
> I thought that I could store the functions in a map ala Function[char[]] so I can reference them as functions["TestFunc"], but I don't know how I can store the templates in any sort of list since they have different parameters/return values.
> I know I can store them as void pointers, but then I need to cast them to the right type before I can use them. Then I have to have a switch statement or something to be able to cast it to the correct type based on the function name.
> 
> I also looked at std.box, and even if it would allow me to store all these functions in a list, I still need to know what object is stored to unbox it.
> 
> The important thing is that I can easily reference the functions by name and get the return value (the script is dynamically typed so no return types there). I also have to use Phobos (as my parser is written in Enki which is Phobos only).
> 
> Any pointers on how I can solve this? I'm sure this is not the best way to do this, and I'm always open for change. Perhaps I have taken the wrong approach here?

So basically you want to put these functions in a big map and then later 
be able to query what their actual parameters and types are?

How are you going to supply the necessary arguments in the end?

You may be able to wrap the functions in a templated wrapper class with 
generic "call(...)" method implemented as a common base class/interface 
  , and some kind of type info retrieval mechanism. Something like this:

  import std.traits;
  interface Callable {
      void call(...);
      TypeInfo argtypes();
  }
  class FuncWrapper(alias Func) : Callable
  {
      alias ParameterTypeTuple!(Func) ArgTup;
      alias ReturnType!(Func) RetT;
      override void call(...) {
         ArgTup args;
         // check to make sure that all _argument's are
         // of the type expected by ArgTup, and copy args
         // one by one to args[i].  This is a little tricky...
         Func(args);
      }
      override TypeInfo argtypes() { return typeid(typeof(Func)); }
  }

But that introduces a fair amount of calling overhead.  And it won't 
work 100% if you start throwing in inout parameters.  I don't think 
TypeInfo really contains everything you need to know about Func's type 
either so you'll probably have to roll your own mechanism to return info 
about the args and return type.

For the return value you'll probably have to make the return value be an 
out parameter of call().

--bb


More information about the Digitalmars-d-learn mailing list