Passing enumeration class into functions. Best practice?
18 次查看(过去 30 天)
显示 更早的评论
Hello,
I have an enumeration defined like this:
classdef myEnum < uint8
enumeration
A (0)
B (1)
C (2)
end
methods (Static)
function out = getDefaultValue()
out = myEnum.B;
end
end
end
and I want to pass the myEnum class into a function like this:
function out = myCaster(in,enum)
% example function with regular enum construction and enum-specific function call
try
out = enum(in);
catch
out = enum.getDefaultValue();
end
end
Obviously, this doesn't work as I can't simply call
>> myCaster(1,myEnum)
Error using myEnum
Input does not correspond to a member of the enumeration class 'myEnum'.
with the classname.
However, I can pass
- A function handle to the classname "@myEnum"
- A string of the classname 'myEnum'
as arguments to the function.
The issue now is that with the first option, I can only call the enum constructor and not the enum-specific functions, e.g.,
enum = @myEnum;
enum(1) % works
enum.getDefaultValue() % fails
With the second option, I'd have to use the 'eval' function (which should be avoided in most cases)
enum = 'myEnum';
eval([enum,'(1)']) % works
eval([enum,'.getDefaultValue()']) % works
My question now:
What is the best practice in that case? Am I missing a clever way to pass an enumeration class as a function argument? If possible, I want to avoid the usage of 'eval' wherever possible.
2 个评论
chrisw23
2022-11-8
You can only pass an object as an argument. In your case this will be a member of your enumeration.
myCaster(1,myEnum.<member>) % just to demonstrate
All methods of your enum class are member methods. So if you want to call the getDefaultValue method, it would be
defVal = myEnum.<member>.getDefaultValue()
回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Enumerations 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!