class scope virtual template functions
Bruno Medeiros
brunodomedeiros+spam at com.gmail
Sat Jun 14 07:57:22 PDT 2008
BCS wrote:
> Reply to Walter,
>
>> BCS wrote:
>>
>>> in my case, I need this syntax
>>>
>>> this.Templet!("foo")(arg)
>>>
>>> to be virtual.
>>>
>>> The use case is inside of dparse where I have template code calling
>>> template code.
>>>
>> You could try parameterizing the class enclosing the template, rather
>> than the template.
>>
>
> I need to be able to have more than one version of the template
>
> for a fuller example
>
> class A
> {
> void Template(char[] s: "foo")(int i) {writef("Hello %d\n", i);}
> void Template(char[] s: "bob")(int i) {writef("See ya %d\n", i);}
> }
>
> class B : A
> {
> void Template(char[] s: "foo")(int i) {for(int j=0;j<i;j++)
> writef("Hello\n");}
> void Template(char[] s: "bob")(int i) {for(int j=0;j<i;j++) writef("See
> ya\n");}}
> }
>
> A a = someA();
> a.Template!("foo")(5);
> a.Template!("bob")(5); // same a, same class different function
>
>
> the actual used code looks something like this:
>
> void CallIt(T,char[] str)(T it)
> {
> it.Template!(str)(arg)
> }
>
> (The reason for that form is rather complicated and irrelevant to this
> thread)
>
>
How about creating normal methods, and normal method override
hierarchy/lineages, and then creating a template that simply selects the
desired method lineage, like this:
--- ---
module test;
class A
{
void Template_foo(int i) {writef("Hello %d\n", i);}
void Template_bob(int i) {writef("See ya %d\n", i);}
template Template(string s: "foo") { alias Template_foo Template; }
template Template(string s: "bob") { alias Template_bob Template; }
}
class B : A
{
override void Template_foo(int i) {for(int j=0;j<i;j++)
writef("Hello\n");}
override void Template_bob(int i) {for(int j=0;j<i;j++) writef("See
ya\n");}
}
void main() {
A a = new B();
a.Template!("foo")(5);
a.Template!("bob")(5); // same a, same class different function
}
--- ---
If you have many method choices, a mixin could be created to
automatically generate all template specializations, such as:
mixin TemplateAliases!("Template", ["foo", "bob", "bar", "xpto"]);
which would generate lines like:
template Template(string s: "foo") { alias Template_foo Template; }
etc.
--
Bruno Medeiros - Software Developer, MSc. in CS/E graduate
http://www.prowiki.org/wiki4d/wiki.cgi?BrunoMedeiros#D
More information about the Digitalmars-d
mailing list