Very hacky solution to class private members
bauss
jj_1337 at live.dk
Thu Jun 9 08:44:50 UTC 2022
On Thursday, 9 June 2022 at 07:24:24 UTC, bauss wrote:
> ...
Some minor modifications for the hiddenFn that allows you to pass
types to a template instead of an array of the parameters.
Also allows one to use a "lambda" for the function body instead
of a string. This lambda has to take the same amount of
parameters that the function takes.
So now it can be done like this:
```d
mixin hiddenFn!("calc", (x,y){
return x * y;
}, Params!(int,int), int, typeof(this));
```
Instead of how to do it before:
```d
mixin hiddenFn!("calc", q{
return x * y;
}, ["int x", "int y"], int, typeof(this));
```
Boilerplate changes:
```d
// Can't use std.algorithm.map in the mixin template, so we need
some terrible function like this ...
static auto stringMap(alias p)(string[] r)
{
string[] result = [];
foreach (n; r) result ~= p(n);
return result;
}
template Params(T...)
{
enum Params = ({
string[] result;
static foreach(i; 0 .. T.length) {
result ~= T[i].stringof ~ " _" ~ to!string(i);
}
return result;
})();
}
mixin template hiddenFn(string name, alias fnBody, string[]
params = [], T = void, Within, string ts =
to!string(xorShift!(Within)))
{
static if (is(T == void))
{
mixin(T.stringof ~ " " ~ name ~ "(string
caller=__FUNCTION__)(" ~ params.join(",") ~ ") if
(caller.startsWith(`" ~ fullyQualifiedName!(Within) ~ "`)) {
fnBody(" ~ stringMap!(p => p.split(" ")[$-1])(params).join(",") ~
"); }");
}
else
{
mixin(T.stringof ~ " " ~ name ~ "(string
caller=__FUNCTION__)(" ~ params.join(",") ~ ") if
(caller.startsWith(`" ~ fullyQualifiedName!(Within) ~ "`)) {
return fnBody(" ~ stringMap!(p => p.split("
")[$-1])(params).join(",") ~"); }");
}
mixin next!(Within);
}
```
More information about the Digitalmars-d
mailing list