Passing enumeration class into functions. Best practice?

조회 수: 14 (최근 30일)
Michael Zauner
Michael Zauner 2022년 11월 7일
댓글: Michael Zauner 2022년 11월 8일
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
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()
Michael Zauner
Michael Zauner 2022년 11월 8일
Thank you for the info! But how would I now call the constructor method e.g., myEnum(1) with a member?

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

Help CenterFile Exchange에서 Enumerations에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by