Passing enumeration class into functions. Best practice?

7 views (last 30 days)
I have an enumeration defined like this:
classdef myEnum < uint8
A (0)
B (1)
C (2)
methods (Static)
function out = getDefaultValue()
out = myEnum.B;
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
out = enum(in);
out = enum.getDefaultValue();
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.
Michael Zauner
Michael Zauner on 8 Nov 2022
Thank you for the info! But how would I now call the constructor method e.g., myEnum(1) with a member?

Sign in to comment.

Answers (0)

Community Treasure Hunt

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

Start Hunting!