Should operator overload methods be virtual?

Don nospam at nospam.com
Tue Dec 1 17:20:27 PST 2009


Steven Schveighoffer wrote:
> On Tue, 01 Dec 2009 13:53:37 -0500, Andrei Alexandrescu 
> <SeeWebsiteForEmail at erdani.org> wrote:
> 
>> Steven Schveighoffer wrote:
>>> On Fri, 27 Nov 2009 18:32:21 -0500, Walter Bright 
>>> <newshound1 at digitalmars.com> wrote:
>>>
>>>> Making them not virtual would also make them not overridable, they'd 
>>>> all be implicitly final.
>>>>
>>>> Is there any compelling use case for virtual operator overloads? 
>>>> Keep in mind that any non-virtual function can still be a wrapper 
>>>> for another virtual method, so it is still possible (with a bit of 
>>>> extra work) for a class to have virtual operator overloads. It just 
>>>> wouldn't be the default.
>>>  I use virtual operator overloads in dcollections.  Such as opCat and 
>>> opAppend.
>>>  collection1 ~= collection2; // 2 different collection types, using 
>>> interfaces instead of templates to avoid code bloat.
>>>  Also, opApply should be by default virtual, since it's not a true 
>>> operator.
>>
>> Would you put up with a couple of forwarding functions?
> 
> Well, I'd certainly put up with it if I had no choice :)  But if I had a 
> choice, I'd choose to keep them virtual.  I have little need for 
> defining bulk operators with templates and mixins, my usage is mainly 
> going to be separate implementations for each operator.  If the compiler 
> could somehow optimize out all instances of the template function to 
> reduce bloat, I think that would make it a little less annoying.

Most of the bloat in my experience comes from that ruddy int->ulong 
implicit conversion, which gets used in the function lookup rules. If 
ints didn't implicitly convert to ulong, 3/4 of my operator overloads 
would disappear -- because then 'long' would be able to do every integer 
type other than ulong.

> 
> One more thing I wonder, can you alias template instantiations?  For 
> example, I have code like this:
> 
> struct S
> {
>   alias opAdd add;
> 
>   void opAdd(int x);
> }
> 
> How does one do that when opAdd is a template with an argument?
> 
> -Steve



More information about the Digitalmars-d mailing list