Taking a function or delegate as argument.
simendsjo
simendsjo at gmail.com
Tue Jan 10 05:05:23 PST 2012
If I want to have a method taking a callback function, I have to specify
if it should take a function or delegate even if I don't really care.
What's the best way to accept either? I cannot see any wrapper for
something like this in std.typecons.
import std.stdio, std.traits;
void f(int i, void function(int) fn) {
fn(i);
}
void d(int i, void delegate(int) dg) {
dg(i);
}
// ugly..
void g(F)(int i, F callback) {
static assert(isSomeFunction!F, "callback is not a function");
static assert(__traits(compiles, { callback(i); }), "callback does
not take int as a parameter");
callback(i);
}
void fcb(int i) {
writeln(i);
}
void main() {
// Error: function t.f (int i, void function(int) fn) is not
callable using argument types (int,void delegate(int))
// f(1, (int i) { writeln(i); });
f(2, &fcb);
d(3, (int i) { writeln(i); });
//Error: function t.d (int i, void delegate(int) dg) is not
callable using argument types (int,void function(int))
//d(4, &fcb);
g(5, &fcb);
g(6, (int i) { writeln(i); });
//g(7, 7); // not a function
//g(8, (string s) { }); // does not take int as arg
}
More information about the Digitalmars-d-learn
mailing list