How to run a default method if a class method is undefined?

5 次查看(过去 30 天)
Say I have a class called A.
a=A();
b=A();
If we call foo123(a,5,b,6) and foo123 is not defined, there will be an error.
I'd like to call a default method in the class that will receive the arguments function's name "foo123" and its arguments (a, 5, b and 6) as varargin.
Is there a way to do so?
I have a class that often needs to handle unknown method calls. Having this would make my life much better. Thanks.
  1 个评论
covariant_cat
covariant_cat 2018-2-24
编辑:Guillaume 2018-2-24
It's related to the dynamic methods question https://www.mathworks.com/matlabcentral/answers/59026-is-it-possible-to-dynamically-add-methods-to-an-object-or-to-build-a-generic-method-that-catches-a, where the answer indicates that this feature has been an enhancement request for many years. In my case it's pretty inconvenient to ask the users of my library to call functions with subsref. Is there a possibility to have in future versions of matlab an inheritable built-in class that this functionality (having a default catch-all method if a method undefined) is enabled?

请先登录,再进行评论。

回答(1 个)

Benjamin Kraus
Benjamin Kraus 2018-2-24
编辑:Benjamin Kraus 2018-2-24
I don't believe there is any way to do this when using the syntax you describe. However, if you use the dot notation, then you can process arbitrary inputs.
foo123(a,5,b,6); % No way to implement desired behavior
a.foo123(5,b,6); % This can be implemented for arbitrary method names.
You can modify this behavior by overloading subsref on the object.
Read this guide for more information: Code Patterns for subsref and subsasgn Methods.
  1 个评论
covariant_cat
covariant_cat 2018-2-24
编辑:per isakson 2018-3-4
It's related to the dynamic methods question https://www.mathworks.com/matlabcentral/answers/59026-is-it-possible-to-dynamically-add-methods-to-an-object-or-to-build-a-generic-method-that-catches-a, where the answer indicates that this feature has been an enhancement request for many years. In my case it's pretty inconvenient to ask the users of my library to call functions with subsref. Is there a possibility to have in future versions of matlab an inheritable built-in class that this functionality (having a default catch-all method if a method undefined) is enabled?

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Get Started with MATLAB 的更多信息

标签

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by