Function overloading
Regan Heath
regan at netmail.co.nz
Tue Jul 31 05:18:51 PDT 2007
Vladimir wrote:
> Ok, it works for that case.
>
> I'm playing with string template parameters. It's a kind of miracle
> for me, a c++ programmer. I made a precompiled wildcard match and
> would like static version to overload as follows:
>
> bool wildcardMatch (T : char[]) (T wild, T str) // general case {
> return false; }
>
> bool wildcardMatch (char[] W) (T str) // static case { return false;
> }
>
> void main() { wildcardMatch ("*", "123"); wildcardMatch !("*")
> ("123"); }
>
> Is that posible?
At first I thought, maybe "static if" would be better than a template
specialization, i.e.
bool wildcardMatch (T : char[]) (T wild, T str)
{
static if (wild == "*") return true;
return false;
}
but of course the value of 'wild' is not known at compile time... or is it?
If it's a constant as in your example 'main' above then it is and the
compiler could theoretically evaluate it.
But then I thought, if you know it's "*" why make a call to
wildcardMatch at all? (after all it will always match)
I came up with:
bool someOtherTpl (T : char[]) (T wild, T str, bool something)
{
if (something)
wildcardMatch(wild, str);
}
someOtherTpl("*", ...
which is a case where you have to code the call to wildcardMatch because
you don't know wild was "*" at that point.
The closest I managed to get with template specialization is:
import std.stdio;
bool wildcardMatch (T) (T wild, T str) // general case
{
writefln("general case");
return false;
}
bool wildcardMatch (W:invariant(char[1]), S) (W wild, S str) // "*" case
{
writefln("* case");
return false;
}
void main()
{
wildcardMatch!(char[])("*asd*".dup, "123".dup);
wildcardMatch!(invariant(char[1]),char[])("*", "123".dup);
wildcardMatch!(invariant(char[1]),char[])("a", "123".dup);
}
Which incorrectly calls the * case for the wild string "a" because of
course it is specializing using a static array of 1 character.
Regan
More information about the Digitalmars-d-learn
mailing list