Suggestion: function template overloading
Sean Kelly
sean at f4.ca
Tue Aug 29 11:44:35 PDT 2006
Kristian wrote:
> On Tue, 29 Aug 2006 21:04:53 +0300, Sean Kelly <sean at f4.ca> wrote:
>
>> Kristian wrote:
>>> It would be very nice if you could overload function templates as
>>> you can in C++. Here is what I mean:
>>> void f(T)(T val) {...}
>>> void f(int val) {...} //error: conflicts with the template function
>>> It would allow you to write special cases for types that need it.
>>
>> void f(T)(T val) {}
>> void f()(int val) {}
>>
>>
>> Sean
>
> Ah, thanks! I missed _that_ one completely... :/
>
> But now I can't get the following to work:
>
> bool equal(T)(T l, T r) {
> return l == r;
> }
> bool equal()(Foo l, Foo r) {
> return l.m_val == r.m_val;
> }
>
> class Foo {
> int m_val = 0;
> }
>
> class Bar(T) {
> this() {
> m_val = new T;
> }
>
> bool eq(T obj) {
> return(equal(m_val, obj)); //error: matches more than one
> template, equal(T) and equal()
> }
>
> T m_val;
> }
>
> void main() {
> Bar!(Foo) bar = new Bar!(Foo);
> Foo foo = new Foo;
>
> printf("%d\n", bar.eq(foo));
> }
>
> It seems that 'binding' is done when 'Bar' is compiled, not when 'bar'
> variable is declared.
In this case, it should choose equal()( Foo ... ) over equal(T)( T ...)
because the Foo overload is the most specialized for the supplied
parameters. Unfortunately, implicit template support in DMD is still
pretty thin so you're probably running into a compiler limitation rather
than a problem with the spec. Instead of:
equal()( Foo l, Foo r )
try:
equal( T : Foo )( Foo l, Foo r )
and see what happens. I've found that with a bit of experimentation
(and perhaps some wrapper code) you can usually get ITI to work as
desired, and simply remove the work-around code as DMD improves.
Sean
More information about the Digitalmars-d
mailing list