opDispatch and UFCS
Artur Skawina
art.08.09 at gmail.com
Tue Jul 2 04:04:06 PDT 2013
On 07/02/13 02:45, cal wrote:
> import std.conv, std.stdio, std.algorithm;
>
> struct S {
> void opDispatch(string s, T...)(T t) if (s.startsWith("foo")) {
> writeln(s);
> }
> }
>
> void main() {
> S s;
> s.foo();
> auto p = s.to!string(); // Error: s.opDispatch!("to") isn't a template
> }
>
> Should the constraint on opDispatch allow the UFCS "to" call on S?
To avoid this kind of issues:
struct S {
template opDispatch(string s) if (s.startsWith("foo")) {
void opDispatch(T...)(T t) {
writeln(s);
}
}
}
And, yes, the compiler should be able to handle your simpler case too,
but currently doesn't (if there are several overloads then the
transformation isn't necessarily this easy). I usually end up doing
something like:
struct S {
static bool _disp(string s) {
if (s.startsWith("foo"))
return true;
// ... other checks, AA lookups, introspection etc.
return false;
}
template opDispatch(string s) if (_disp(s)) {
void opDispatch(T...)(T t) {
writeln(s);
}
}
}
Dealing with the various frontend quirks can be fun.
artur
More information about the Digitalmars-d-learn
mailing list