3 ms·
Well, for example: import std.stdio; struct Math(string Op) { static auto eval(T, U)(T l, U r) { static if (Op == "+") return l + r;
by ZootAllures91 7y ago
Well, for example:
import std.stdio;
struct Math(string Op) {
static auto eval(T, U)(T l, U r) {
static if (Op == "+")
return l + r;
else static if (Op == "-")
return l - r;
else static if (Op == "*")
return l * r;
else static if (Op == "/")
return l / r;
}
}
static immutable auto result = Math!("+").eval(1, 2) + Math!("*").eval(3.0, 3.0);
void main() {
writeln(result);
}
You'll never be able to do anything like that in Rust until const generics are not only complete on their own, but also fully compatible with "const fn".
- mhh__ 7y agoAssuming I formatted it right, I made your example shorter import std; template Math(char Op) { auto eval(T, U)(T l, U r) { static foreach(x; "+-*/") { if (Op == x) mixin("return l ", x, " r;"); } } } static immutable result = Math!('+').eval(1, 2) + Math!('*').eval(3.0, 3.0); void main() { writeln(result); }
- ZootAllures91 7y agoYeah, that works too. I was trying not to get too crazy I guess. And also just show all the various levels of "static".