Skip to content

Instantly share code, notes, and snippets.

@Jaffe-
Created April 10, 2017 20:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jaffe-/b027287a884fc2e173a65601ec242676 to your computer and use it in GitHub Desktop.
Save Jaffe-/b027287a884fc2e173a65601ec242676 to your computer and use it in GitHub Desktop.
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