Dictionary of Templated Functions

jwatson-CO-edu real.name at colorado.edu
Sat Sep 10 22:35:48 UTC 2022


On Saturday, 10 September 2022 at 22:13:01 UTC, frame wrote:
> On Saturday, 10 September 2022 at 00:24:11 UTC, jwatson-CO-edu 
> wrote:
>> Hello,
>> I'm trying to create a dictionary of templated function 
>> pointers.  The functions should return `bool` and take a 
>> differently-typed dynamics arrays `T[]` as an argument.
>
> This won't work as you might expect. Your container would need 
> to support multiple types and may need overloads of operators 
> to become that magic.
>
> But lets begin with a simple type. Consider your example fixed:
>
> ```d
> alias FuncDict(T) = bool function(T[])[string]; // alias needs 
> T as parameter too...
>
> FuncDict!(string) lookup; // ...so we can instantiate a 
> FuncDict with T = string
>
> void main()
> {
>     lookup["foo"] = function bool(string[] args) { return true; 
> };
> }
> ```
>
> As you can see `T` is bound to `string` here and cannot be 
> something else.

     Ah, this gives me more information on how to use `alias`es, 
thank you!
     I can see that I have wished for a magical thing.  So, my 
solution will be to construct a catch-all struct `Payload` and 
have that be my argument type from which various functions can 
draw the data of their choice.

```d
struct Payload{
     double[] dbbls;
     string[] strns;
     // Probably others ...
}
```

     Application is a Dlang implementation of Little Scheme, from 
the book "The Little Schemer".   For it, I need a menu of 
"primitive" base functions that form the foundation of anything 
you might ask the interpreter to do. (Hence my wish for a 
multi-type dict.)
     Thanks again!


More information about the Digitalmars-d-learn mailing list