Delegates and classes for custom code.
Simen Kjærås
simen.kjaras at gmail.com
Wed Apr 18 06:03:54 UTC 2018
On Wednesday, 18 April 2018 at 01:12:33 UTC, Chris Katko wrote:
> My only questions are:
[snip]
How's about this one:
import std.stdio : writefln;
struct data_to_access_t
{
int tacos;
}
class Abc(T, alias Fn) {
T data;
this(T data) {
this.data = data;
}
void execute() {
Fn(data);
}
}
Abc!(T, Fn) abc(alias Fn, T)(T data) {
return new Abc!(T, Fn)(data);
}
unittest {
data_to_access_t d;
auto a = abc!((f) => writefln("test %d", f.tacos))(d);
a.execute();
}
One problem with this approach is that two seemingly identical
instantiations are different types. This may or may not be a
problem in your specific case. If it is:
import std.stdio : writefln;
import std.functional : toDelegate;
struct data_to_access_t
{
int tacos;
}
class Abc(T) {
T data;
void delegate(T) Fn;
this(T data, void delegate(T) Fn) {
this.data = data;
this.Fn = Fn;
}
void execute() {
Fn(data);
}
}
Abc!(T) abc(alias Fn, T)(T data) {
static if (__traits(isTemplate, Fn))
return new Abc!(T)(data, Fn!T);
else
return new Abc!(T)(data, Fn.toDelegate);
}
unittest {
data_to_access_t d;
auto a = abc!((f) => writefln("test %d", f.tacos))(d);
auto b = abc!((data_to_access_t f) => writefln("test %d",
f.tacos))(d);
a.execute();
b.execute();
}
--
Simen
More information about the Digitalmars-d-learn
mailing list