On Friday, 28 February 2020 at 08:08:59 UTC, Виталий Фадеев wrote:
Searching for beauty readable code...
The pattern throughout Phobos is static tests, like isInputRange!R
So something like this:
import std.stdio;
import std.traits;
template canOnKey(T) {
static if (__traits(hasMember, T, "onKey"))
enum canOnKey = isCallable!(__traits(getMember, T,
"onKey"));
else
enum canOnKey = false;
}
struct A { void onKey() { writeln("called A"); } }
struct B { }
struct C { bool onKey = false; }
void maybeKey(T)(T o) if (canOnKey!T) {
o.onKey();
}
void maybeKey(T)(T o) if (!canOnKey!T) { }
void main() {
auto a = A(), b = B(), c = C();
maybeKey(a);
maybeKey(b);
maybeKey(c);
}
output:
called A
(and no other output)
Of course in this exact instance it would be simpler to write
void maybeKey(T)(T o) {
static if (canOnKey!T)
o.onKey();
}
And rather than lots of specific hasThisExactMethod!T tests, it
might be nice if in your actual program there's a 'class' of
grouped properties that you can test for all at once, again
like isInputRange!T and friends.