Code example for function/delegate as template argument ?
H. S. Teoh via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed May 4 04:32:47 PDT 2016
On Wed, May 04, 2016 at 06:21:36AM +0000, chmike via Digitalmars-d-learn wrote:
> Hello,
>
> I failed to find some code example for a template class/struct that
> accept a function/delegate as template argument. All examples I could
> find use simple value types like int or double.
The usual way is to use an alias argument:
class MyClass(alias fun)
if (is(typeof(fun(0)))) // assuming fun takes 1 int argument
{
void method() {
fun(0);
}
}
> I piggy bag another question. Defining a function/delegate as function
> argument is shown in examples. What I could not find is how would I
> pass an object instance with a method to call ? In C++ we use
> std::bind. How do we do that in D ?
You probably need a delegate, since a function (== function pointer) in
D is a pointer to a (module-global) function with no context. If you
need a context, e.g., an object instance, you need a delegate. Example:
class C {
void method(int x) {
import std.stdio;
writeln("bing!");
}
}
void fun(void delegate(int) dg) {
dg(1);
}
void main() {
auto c = new C;
fun(&c.method);
}
T
--
Long, long ago, the ancient Chinese invented a device that lets them see through walls. It was called the "window".
More information about the Digitalmars-d-learn
mailing list