Templating with Function Pointers?

Maxime Chevalier-Boisvert maximechevalierb at gmail.com
Wed Dec 11 21:53:37 PST 2013


Thanks, I think the std.concurrency code demonstrates exactly 
what I need :)

On Thursday, 12 December 2013 at 05:07:11 UTC, Ali Çehreli wrote:
> On 12/11/2013 06:43 PM, Maxime Chevalier-Boisvert wrote:
>
> > Is it possible to template based on a function pointer
> argument? If so,
> > is it possible to use static ifs to know the return type or
> the argument
> > types of the function pointer's signature, as well as how
> many arguments
> > it takes?
>
> That one is pretty straightforward:
>
> import std.string;
>
> void temp(Func)(Func func)
> {
>     static if (is (Func == int function(double))) {
>         pragma(msg, "Found an int(double)");
>
>     } else static if (is (Func == ReturnT function(string, 
> size_t), ReturnT)) {
>         pragma(msg, format("This one returns %s", 
> ReturnT.stringof));
>     }
> }
>
> int foo(double d)
> {
>     return 42;
> }
>
> struct S
> {}
>
> S bar(string s, size_t st)
> {
>     return S.init;
> }
>
> void main()
> {
>     temp(&foo);
>     temp(&bar);
> }
>
> It is also possible to use alias template parameters or 
> variadic template parameters. You may want to look at 
> std.concurrency's receive() function implementation for more 
> ideas.
>
> Ali



More information about the Digitalmars-d-learn mailing list