Templating with Function Pointers?

Ali Çehreli acehreli at yahoo.com
Wed Dec 11 21:07:11 PST 2013


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