Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Forwarding to calls to objects of different class/struct
import std.stdio;
import std.algorithm;
struct S {
int x[];
void foo(int x) {
this.x ~= x;
}
void bar() {
writeln("Contains: ", x);
}
auto call(alias func, T...)(T args) {
return func(args);
}
auto reduce(alias func)() {
return x.reduce!(func);
}
}
class Container {
S[10] ss;
void call_for_each(alias func, T...)(T args) {
foreach(ref s; ss) {
s.call!func(args);
}
}
void foo(int x) {
call_for_each!(S.foo)(x);
}
void bar() {
call_for_each!(S.bar)();
}
auto reduce(alias func)() {
return ss[]
.map!(t => t.reduce!func)
.reduce!(func);
}
}
void main() {
auto test = new Container();
test.foo(10);
test.foo(20);
test.foo(30);
test.bar();
auto x = test.reduce!((a, b) => a + b); // Fails: template instance reduce!((a, b) => a + b) cannot use local '__lambda1' as parameter to non-global template reduce(alias fun)()
auto x = test.reduce!((int a, int b) => a + b); // Compiles
writeln(x);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment