Passing enumeration class into functions. Best practice?
7 views (last 30 days)
Show older comments
Michael Zauner on 7 Nov 2022
Commented: Michael Zauner on 8 Nov 2022
I have an enumeration defined like this:
classdef myEnum < uint8
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
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.
Find more on Signal Attributes and Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!