Overloading operators for a class

余生长醉 提交于 2020-01-14 07:24:21

问题


Let's say I have the following class:

class A {
    has $.val;

    method Str { $!val ~ 'µ'  }  
}

# Is this the right way of doing it?
multi infix:<~>(A:D $lhs, A:D $rhs) {
    ('(', $lhs.val, ',', $rhs.val, ')', 'µ').join;
}

How would I overload an operator (e.g., +) for a class in the same manner as Str in the previous class?

I guess this only works for methods that are invoked on an instance object and using the multi operator-type:<OP>(T $lhs, T $rhs) { } syntax for operators is the right way to go about it but I'm unsure.

For instance, in Python there seems to be a correspondence between special methods named after the operators (e.g., operator.__add__) and the operators (e.g., +). Furthermore, any operator overloading for a custom class is done inside the class.


回答1:


In Perl 6, operators are considered part of the current language. All things that relate to the current language are defined lexically (that is, my-scoped). Therefore, a multi sub is the correct thing to use.

If putting this code in a module, you would probably also want to mark the multi for the operator with is export:

multi infix:<~>(A:D $lhs, A:D $rhs) is export {
    ('(', $lhs.val, ',', $rhs.val, ')', 'µ').join;
}

So that it will be available to users who use or import the module (use is in fact defined in terms of import, and import imports symbols into the lexical scope).

While there are some operators that by default delegate to methods (for example, prefix:<+> calls Numeric), there's no 1:1 relation between the two, and for most operators their implementation is directly in the operator sub (or spread over many multi subs).

Further, the set of operators is open, so one is not restricted to overloading existing operators, but can also introduce new ones. This is encouraged when the new meaning for the operator is not clearly related to the normal semantics of the symbol used; for example, overloading + to do matrix addition would be sensible, but for something that couldn't possibly be considered a kind of addition, a new operator would be a better choice.




回答2:


class A {
    has $.val;

    method Str { $!val ~ 'µ'  }
}

multi infix:<~>(A:D $lhs, A:D $rhs) {
    ('(', $lhs.val, ',', $rhs.val, ')', 'µ').join;
}

dd A.new(val => "A") ~ A.new(val  => "B"); # "(A,B)µ"

So yes, that is the correct way. If you want to override +, then the name of the sub to create is infix:<+>.

You can also provide the case for type objects by using the :U "type smiley", e.g.:

multi infix:<~>(A:U $lhs, A:U $rhs) {
    'µ'
}

Hope this answers your question.



来源:https://stackoverflow.com/questions/55814075/overloading-operators-for-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!