Template elegance?
David Monagle via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Jun 3 02:10:20 PDT 2015
Hi guys,
I was hoping some of you more experience D guys could educate me
on this one.
Given the following code:
///////
// Template function
bool shouldValue(alias operation, string description, E, V)(lazy
E expression, V value, string name="Value", string file =
__FILE__, typeof(__LINE__) line = __LINE__) {
if (operation(expression, value)) return true;
throw new FeatureTestException(format("%s should %s %s, but was
actually %s", name, description, value, expression), file, line);
}
// Utility functions that use the above template
bool shouldEqual(E, V)(lazy E expression, V value, string
name="Value", string file = __FILE__, typeof(__LINE__) line =
__LINE__) {
return shouldValue!((e, v) => e == v, "equal")(expression,
value, name, file, line);
}
bool shouldBeGreaterThan(E, V)(lazy E expression, V value, string
name="Value", string file = __FILE__, typeof(__LINE__) line =
__LINE__) {
return shouldValue!((e, v) => e > v, "equal")(expression, value,
name, file, line);
}
///////
The above works just fine. If I call something like:
value.shouldBeGreaterThan(5)
I get the expected results.
What I was looking for is a more elegant way of defining those
secondary functions. Originally I was hoping I could do something
like:
enum shouldEqual(E, V) = shouldValue((e, v) => e == v, "equal",
E, V);
But that doesn't work as any call to result.shouldEqual(5) does
results in the template being called with no TEMPLATE parameters.
I understand this, however I was hoping there was a nice way of
defining this functionality. I concede that my code above may
already be as short and concise as I can get it.
Thanks in advance!
David.
More information about the Digitalmars-d-learn
mailing list