Duck typing and safety.
Mafi
mafi at example.org
Fri Aug 13 10:16:43 PDT 2010
Am 13.08.2010 19:01, schrieb simendsjo:
> import std.stdio;
>
> struct S
> {
> void shittyNameThatProbablyGetsRefactored() { };
> }
>
> void process(T)(T s)
> {
> static if( __traits(hasMember, T,
> "shittyNameThatProbablyGetsRefactored"))
> {
> writeln("normal processing");
> }
> else
> {
> writeln("Start nuclear war!");
> }
> }
>
>
> void main()
> {
> S s;
> process(s);
> }
>
>
> If you rename S's method, process() does something completely different
> without a compile time error. By using interfaces this is avoided as the
> rename would break the interface.
As I understand this, you want t never start a nuclear war (lol) so do
something like this:
void process(T)(T s) if ( __traits(hasMember, T,
"shittyNameThatProbablyGetsRefactored")) {...}
The if here is a template constraint, which is part of the signature
(which means you can overload with those). If you try to instantiate
your template in a wrong manner, you get a nice ct error at the
instantiation.
Then you can remove the unreachable 'war'-branch.
Mafi
More information about the Digitalmars-d-learn
mailing list