Passing enumeration class into functions. Best practice?

25 visualizzazioni (ultimi 30 giorni)
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 Commenti
chrisw23
chrisw23 il 8 Nov 2022
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 il 8 Nov 2022
Thank you for the info! But how would I now call the constructor method e.g., myEnum(1) with a member?

Accedi per commentare.

Risposte (0)

Categorie

Scopri di più su Enumerations in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by