www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - [draft, proposal] Virtual template functions

reply Dmitry Olshansky <dmitry.olsh gmail.com> writes:
I'm reiterating prior info on the subject and provide some motivating 
examples. For those convinced of necessity of virtual function templates 
already - skip to the bottom ;)

Ultimately template is a way to use the same source code for multiple 
entities (typically called instantiations).
In the light of the above simple definition it's painfully obvious that 
if functions generated by template are final vs virtual is completely 
separate orthogonal matter.
The fact that templates are final is rather a happenstance,
"it's 'cause it's too hard, lad" kind of thing.

The fundamental problem is that given an interface
interface I
{
	TA funcA();
	TB funcB();
	TC funcC();
	...
}

compiler needs to plot _final_ layout of a v-table so that separate 
compilation works without hassle. (there are possible ways around it, 
though non-trivial and breaking current toolchains).

Now since even constrained template technically can accommodate infinite 
number of instantiations it sure becomes problematic.

But surely the template below has exactly X instantiations,
since there is only X operators in the whole D language that are ever 
overloadable, X being constant (sorry didn't care to count).

interface Matrix
{
	void opOpAssign(string op)(Matrix rhs);
}

And this one is even down to 3:

interface Matrix
{
	void opOpAssign(string op)(Matrix rhs)
	if(op == "+" || op == "-" || op == "*");
}

Of course, having compiler to deduce these kind of special cases can be 
described as a fragile hack at best. Thus a more clean and general 
solution is proposed.

Before moving on to syntax and the feature itself. Another motivating 
example to illustrate a need for virtual functions to be templates.
Though I'm you know a lot of uses cases as well, so feel free to skip it.

Suppose you define Set as interface for sets, and provide some 
implementations of it like BitSet, HashSet, TreeSet, SparceSet.

Now we are back to operator overloading, some might argue that having 
final operators is enough, it's not:

interface Set(V, K)
{
	V get(K key);
	void put(V value, K key);
	void remove(K key);
	//even opApply won't save us ;)
	int opApply(scope delegate(K, V));
	
	void opOpAssign(string op)(Set rhs)
	{
		
		//foreach(k, v; rhs)
		//	remove(k);
		//Okay, now try to be efficient, punk !
		...
	}
}

It's immediately obvious that doing low-level operations via high-level 
primitives is no good. Certain combination of sets are obviously can be 
done faster. And for instance 2 small enough bitsets can be merged in a 
blink of an eye, (similar things for sparse set). And nobody is willing 
to give up speed nor polymorphism.

(e.g. Set & Set should use the best overload for '&' for concrete sets 
at hand == virtual operator).

The only current way is forwarding to virtual methods and that may work. 
Though templates and new operator overloading in particular aim to 
reduce amount of repetition and boilerplate.


Enough of talk, to the proposal, synopsis is to enhance template 
declaration:

T func(string id, T, Args...)(...)
	if( ... ) //optional
	for(	//optional
		id : "a", "b", "c";
		T: double, float;
		Args : (int, int), (uint, int), (int, uint);
	)//syntax debatable, 'for' is not ;)

It would then instantate all of possible overloads immediately in this 
particular module.  (another use case for it is explicit instantiation 
for shared libraries)

If it happens to be inside of class/interface the by default all of 
overloads would work as virtual.

Other then this for implies the following if condition ANDed together to 
existing if clause if any:
.... & (
(id == "a" || id == "b" || id == "c") &&
(is(T == double)|| is(T == float)) &&
(
		(is(Args[0] == int) && is(Args[1]==int))
	|| 	(is(Args[0] == uint) && is(Args[1]==int))
	||	(is(Args[0] == int) && is(Args[1]==uint))

)

)
A remarkable boilerplate, underlines the fact that trying to have 
compiler to deduce all types from it for you is not realistic in general 
case.

Of course the coma separated typelists can be constructed via 
meta-programming. In fact all tuples should be flattened (as is 
everywhere else).

And that's it, so new 'for' clause for templates does:
	- explicitly instantes entities, ensuring bounded number of 
instantiations (makes virtual possible)
	- provides alternative sugar for 'if' syntax
	- fits with the rest of language, via typetuple and meta-programming
	- allows simple techniques to curb down accidental duck-typing

-- 
Dmitry Olshansky
May 29 2012
next sibling parent Gor Gyolchanyan <gor.f.gyolchanyan gmail.com> writes:
--90e6ba61528c213c9904c12eb217
Content-Type: text/plain; charset=UTF-8

On Tue, May 29, 2012 at 3:59 PM, Dmitry Olshansky <dmitry.olsh gmail.com>wrote:

 I'm reiterating prior info on the subject and provide some motivating
 examples. For those convinced of necessity of virtual function templates
 already - skip to the bottom ;)

 Ultimately template is a way to use the same source code for multiple
 entities (typically called instantiations).
 In the light of the above simple definition it's painfully obvious that if
 functions generated by template are final vs virtual is completely separate
 orthogonal matter.
 The fact that templates are final is rather a happenstance,
 "it's 'cause it's too hard, lad" kind of thing.

 The fundamental problem is that given an interface
 interface I
 {
        TA funcA();
        TB funcB();
        TC funcC();
        ...
 }

 compiler needs to plot _final_ layout of a v-table so that separate
 compilation works without hassle. (there are possible ways around it,
 though non-trivial and breaking current toolchains).

 Now since even constrained template technically can accommodate infinite
 number of instantiations it sure becomes problematic.

 But surely the template below has exactly X instantiations,
 since there is only X operators in the whole D language that are ever
 overloadable, X being constant (sorry didn't care to count).

 interface Matrix
 {
        void opOpAssign(string op)(Matrix rhs);
 }

 And this one is even down to 3:

 interface Matrix
 {
        void opOpAssign(string op)(Matrix rhs)
        if(op == "+" || op == "-" || op == "*");
 }

 Of course, having compiler to deduce these kind of special cases can be
 described as a fragile hack at best. Thus a more clean and general solution
 is proposed.

 Before moving on to syntax and the feature itself. Another motivating
 example to illustrate a need for virtual functions to be templates.
 Though I'm you know a lot of uses cases as well, so feel free to skip it.

 Suppose you define Set as interface for sets, and provide some
 implementations of it like BitSet, HashSet, TreeSet, SparceSet.

 Now we are back to operator overloading, some might argue that having
 final operators is enough, it's not:

 interface Set(V, K)
 {
        V get(K key);
        void put(V value, K key);
        void remove(K key);
        //even opApply won't save us ;)
        int opApply(scope delegate(K, V));

        void opOpAssign(string op)(Set rhs)
        {

                //foreach(k, v; rhs)
                //      remove(k);
                //Okay, now try to be efficient, punk !
                ...
        }
 }

 It's immediately obvious that doing low-level operations via high-level
 primitives is no good. Certain combination of sets are obviously can be
 done faster. And for instance 2 small enough bitsets can be merged in a
 blink of an eye, (similar things for sparse set). And nobody is willing to
 give up speed nor polymorphism.

 (e.g. Set & Set should use the best overload for '&' for concrete sets at
 hand == virtual operator).

 The only current way is forwarding to virtual methods and that may work.
 Though templates and new operator overloading in particular aim to reduce
 amount of repetition and boilerplate.


 Enough of talk, to the proposal, synopsis is to enhance template
 declaration:

 T func(string id, T, Args...)(...)
        if( ... ) //optional
        for(    //optional
                id : "a", "b", "c";
                T: double, float;
                Args : (int, int), (uint, int), (int, uint);
        )//syntax debatable, 'for' is not ;)

 It would then instantate all of possible overloads immediately in this
 particular module.  (another use case for it is explicit instantiation for
 shared libraries)

 If it happens to be inside of class/interface the by default all of
 overloads would work as virtual.

 Other then this for implies the following if condition ANDed together to
 existing if clause if any:
 .... & (
 (id == "a" || id == "b" || id == "c") &&
 (is(T == double)|| is(T == float)) &&
 (
                (is(Args[0] == int) && is(Args[1]==int))
        ||      (is(Args[0] == uint) && is(Args[1]==int))
        ||      (is(Args[0] == int) && is(Args[1]==uint))

 )

 )
 A remarkable boilerplate, underlines the fact that trying to have compiler
 to deduce all types from it for you is not realistic in general case.

 Of course the coma separated typelists can be constructed via
 meta-programming. In fact all tuples should be flattened (as is everywhere
 else).

 And that's it, so new 'for' clause for templates does:
        - explicitly instantes entities, ensuring bounded number of
 instantiations (makes virtual possible)
        - provides alternative sugar for 'if' syntax
        - fits with the rest of language, via typetuple and meta-programming
        - allows simple techniques to curb down accidental duck-typing

 --
 Dmitry Olshansky

This is a really awesome idea! Not only does it solve a lot of problems, it also looks very intuitive and doesn't break existing code. If D was the first language to have virtual template methods, that would be a huge credit to the language! +1! -- Bye, Gor Gyolchanyan. --90e6ba61528c213c9904c12eb217 Content-Type: text/html; charset=UTF-8 Content-Transfer-Encoding: quoted-printable <div class=3D"gmail_quote">On Tue, May 29, 2012 at 3:59 PM, Dmitry Olshansk= y <span dir=3D"ltr">&lt;<a href=3D"mailto:dmitry.olsh gmail.com" target=3D"= _blank">dmitry.olsh gmail.com</a>&gt;</span> wrote:<br><blockquote class=3D= "gmail_quote" style=3D"margin:0 0 0 .8ex;border-left:1px #ccc solid;padding= -left:1ex"> I&#39;m reiterating prior info on the subject and provide some motivating e= xamples. For those convinced of necessity of virtual function templates alr= eady - skip to the bottom ;)<br> <br> Ultimately template is a way to use the same source code for multiple entit= ies (typically called instantiations).<br> In the light of the above simple definition it&#39;s painfully obvious that= if functions generated by template are final vs virtual is completely sepa= rate orthogonal matter.<br> The fact that templates are final is rather a happenstance,<br> &quot;it&#39;s &#39;cause it&#39;s too hard, lad&quot; kind of thing.<br> <br> The fundamental problem is that given an interface<br> interface I<br> {<br> =C2=A0 =C2=A0 =C2=A0 =C2=A0TA funcA();<br> =C2=A0 =C2=A0 =C2=A0 =C2=A0TB funcB();<br> =C2=A0 =C2=A0 =C2=A0 =C2=A0TC funcC();<br> =C2=A0 =C2=A0 =C2=A0 =C2=A0...<br> }<br> <br> compiler needs to plot _final_ layout of a v-table so that separate compila= tion works without hassle. (there are possible ways around it, though non-t= rivial and breaking current toolchains).<br> <br> Now since even constrained template technically can accommodate infinite nu= mber of instantiations it sure becomes problematic.<br> <br> But surely the template below has exactly X instantiations,<br> since there is only X operators in the whole D language that are ever overl= oadable, X being constant (sorry didn&#39;t care to count).<br> <br> interface Matrix<br> {<br> =C2=A0 =C2=A0 =C2=A0 =C2=A0void opOpAssign(string op)(Matrix rhs);<br> }<br> <br> And this one is even down to 3:<br> <br> interface Matrix<br> {<br> =C2=A0 =C2=A0 =C2=A0 =C2=A0void opOpAssign(string op)(Matrix rhs)<br> =C2=A0 =C2=A0 =C2=A0 =C2=A0if(op =3D=3D &quot;+&quot; || op =3D=3D &quot;-= &quot; || op =3D=3D &quot;*&quot;);<br> }<br> <br> Of course, having compiler to deduce these kind of special cases can be des= cribed as a fragile hack at best. Thus a more clean and general solution is= proposed.<br> <br> Before moving on to syntax and the feature itself. Another motivating examp= le to illustrate a need for virtual functions to be templates.<br> Though I&#39;m you know a lot of uses cases as well, so feel free to skip i= t.<br> <br> Suppose you define Set as interface for sets, and provide some implementati= ons of it like BitSet, HashSet, TreeSet, SparceSet.<br> <br> Now we are back to operator overloading, some might argue that having final= operators is enough, it&#39;s not:<br> <br> interface Set(V, K)<br> {<br> =C2=A0 =C2=A0 =C2=A0 =C2=A0V get(K key);<br> =C2=A0 =C2=A0 =C2=A0 =C2=A0void put(V value, K key);<br> =C2=A0 =C2=A0 =C2=A0 =C2=A0void remove(K key);<br> =C2=A0 =C2=A0 =C2=A0 =C2=A0//even opApply won&#39;t save us ;)<br> =C2=A0 =C2=A0 =C2=A0 =C2=A0int opApply(scope delegate(K, V));<br> =C2=A0 =C2=A0 =C2=A0 =C2=A0<br> =C2=A0 =C2=A0 =C2=A0 =C2=A0void opOpAssign(string op)(Set rhs)<br> =C2=A0 =C2=A0 =C2=A0 =C2=A0{<br> =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0<br> =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0//foreach(k, v; rhs= )<br> =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0// =C2=A0 =C2=A0 = =C2=A0remove(k);<br> =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0//Okay, now try to = be efficient, punk !<br> =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0...<br> =C2=A0 =C2=A0 =C2=A0 =C2=A0}<br> }<br> <br> It&#39;s immediately obvious that doing low-level operations via high-level= primitives is no good. Certain combination of sets are obviously can be do= ne faster. And for instance 2 small enough bitsets can be merged in a blink= of an eye, (similar things for sparse set). And nobody is willing to give = up speed nor polymorphism.<br> <br> (e.g. Set &amp; Set should use the best overload for &#39;&amp;&#39; for co= ncrete sets at hand =3D=3D virtual operator).<br> <br> The only current way is forwarding to virtual methods and that may work. Th= ough templates and new operator overloading in particular aim to reduce amo= unt of repetition and boilerplate.<br> <br> <br> Enough of talk, to the proposal, synopsis is to enhance template declaratio= n:<br> <br> T func(string id, T, Args...)(...)<br> =C2=A0 =C2=A0 =C2=A0 =C2=A0if( ... ) //optional<br> =C2=A0 =C2=A0 =C2=A0 =C2=A0for( =C2=A0 =C2=A0//optional<br> =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0id : &quot;a&quot;,= &quot;b&quot;, &quot;c&quot;;<br> =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0T: double, float;<b= r> =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0Args : (int, int), = (uint, int), (int, uint);<br> =C2=A0 =C2=A0 =C2=A0 =C2=A0)//syntax debatable, &#39;for&#39; is not ;)<br=

It would then instantate all of possible overloads immediately in this part= icular module. =C2=A0(another use case for it is explicit instantiation for= shared libraries)<br> <br> If it happens to be inside of class/interface the by default all of overloa= ds would work as virtual.<br> <br> Other then this for implies the following if condition ANDed together to ex= isting if clause if any:<br> .... &amp; (<br> (id =3D=3D &quot;a&quot; || id =3D=3D &quot;b&quot; || id =3D=3D &quot;c&qu= ot;) &amp;&amp;<br> (is(T =3D=3D double)|| is(T =3D=3D float)) &amp;&amp;<br> (<br> =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0 =C2=A0(is(Args[0] =3D=3D = int) &amp;&amp; is(Args[1]=3D=3Dint))<br> =C2=A0 =C2=A0 =C2=A0 =C2=A0|| =C2=A0 =C2=A0 =C2=A0(is(Args[0] =3D=3D uint)= &amp;&amp; is(Args[1]=3D=3Dint))<br> =C2=A0 =C2=A0 =C2=A0 =C2=A0|| =C2=A0 =C2=A0 =C2=A0(is(Args[0] =3D=3D int) = &amp;&amp; is(Args[1]=3D=3Duint))<br> <br> )<br> <br> )<br> A remarkable boilerplate, underlines the fact that trying to have compiler = to deduce all types from it for you is not realistic in general case.<br> <br> Of course the coma separated typelists can be constructed via meta-programm= ing. In fact all tuples should be flattened (as is everywhere else).<br> <br> And that&#39;s it, so new &#39;for&#39; clause for templates does:<br> =C2=A0 =C2=A0 =C2=A0 =C2=A0- explicitly instantes entities, ensuring bound= ed number of instantiations (makes virtual possible)<br> =C2=A0 =C2=A0 =C2=A0 =C2=A0- provides alternative sugar for &#39;if&#39; s= yntax<br> =C2=A0 =C2=A0 =C2=A0 =C2=A0- fits with the rest of language, via typetuple= and meta-programming<br> =C2=A0 =C2=A0 =C2=A0 =C2=A0- allows simple techniques to curb down acciden= tal duck-typing<span class=3D"HOEnZb"><font color=3D"#888888"><br> <br> -- <br> Dmitry Olshansky<br> </font></span></blockquote></div><br>This is a really awesome idea! Not onl= y does it solve a lot of problems, it also looks very intuitive and doesn&#= 39;t break existing code. If D was the first language to have virtual templ= ate methods, that would be a huge credit to the language!<div> +1!</div><div><div><div><br></div>-- <br>Bye,<br>Gor Gyolchanyan.<br> </div></div> --90e6ba61528c213c9904c12eb217--
May 29 2012
prev sibling parent reply Andrej Mitrovic <andrej.mitrovich gmail.com> writes:
On 5/29/12, Dmitry Olshansky <dmitry.olsh gmail.com> wrote:
 I'm reiterating prior info on the subject and provide some motivating
 examples. For those convinced of necessity of virtual function templates
 already - skip to the bottom ;)

I've run into an issue like this, currently I use this sort of workaround: class Base { abstract void run(); void runAll(this Child)(Child ch) { foreach (i; 0 .. 10) // demo ch.templateMethod(i); } } class Child : Base { override void run() { runAll(this); } void templateMethod(T)(T t) { } } void main() { auto ch = new Child; ch.run(); } All subclasses of Base need to implement 'templateMethod', but it has to be a templated function. Unfortunately that means it can't be virtual so I'm using a 'this' template parameter in a base function that has to be called. Not very pretty!
May 29 2012
parent Dmitry Olshansky <dmitry.olsh gmail.com> writes:
On 29.05.2012 21:04, Andrej Mitrovic wrote:
 On 5/29/12, Dmitry Olshansky<dmitry.olsh gmail.com>  wrote:
 I'm reiterating prior info on the subject and provide some motivating
 examples. For those convinced of necessity of virtual function templates
 already - skip to the bottom ;)

I've run into an issue like this, currently I use this sort of workaround: class Base { abstract void run(); void runAll(this Child)(Child ch) { foreach (i; 0 .. 10) // demo ch.templateMethod(i); } } class Child : Base { override void run() { runAll(this); } void templateMethod(T)(T t) { } } void main() { auto ch = new Child; ch.run(); }

Would this work if say: Base ch = new Child; ch.run(); Since all this template this parameter stuff is arcane to me :) In any event it look like doing hand-written thunks. And that's clear indication to me that it needs a better hook in compiler.
 All subclasses of Base need to implement 'templateMethod', but it has
 to be a templated function. Unfortunately that means it can't be
 virtual so I'm using a 'this' template parameter in a base function
 that has to be called. Not very pretty!

The bloat is the same, and even some extra call overhead if I'm not mistaken. -- Dmitry Olshansky
May 29 2012