noearchimede
noearchimede

Reputation: 187

Passing any enum of a given type as function parameter

I'm working on a project for an AVR microcontroller using the Arduino framework.

I'm building a simple error tracking system structured as a class (ErrorManager). I have defined a couple of functions like

void ErrorManager::error(??? errorCode) { // more on ??? later
    // rise error in some way
}

I want to define error codes separately in different modules that make up this project. In each module, I would like to define an enum class containing the codes for that module, and then pass them to the error function above:

namespace someNamespace /* or class SomeClass */ {

// cointains error codes for this class/module/part of the code
enum class ErrorCodes : unsigned int { 
    none = 0,
    anError,
    someOtherError
}

void foo() {
    error(ErrorCodes::anError);
}

}

(let errManager be the ErrorManager object declared in one module of my project)

I could accomplish this by writing unsigned int in ??? and using an enum instead of an enum class, but that would mean that the error code names would be in scope in the whole module namespace or, at least, in the whole class where they are defined, and I would rather avoid this.

Is there a way to do this with an enum class? For example, something to write in ??? which means "Take any Enum (with unsigned int, or some a typedefined type, or even any integer type) as parameter"?

Upvotes: 1

Views: 337

Answers (1)

Thomas Weller
Thomas Weller

Reputation: 59410

It seems you need a template:

template <typename T>   
void /*ErrorManager::*/error(T x) 
{ 
    unsigned int errorcode = (unsigned int)x;
    // Do something with it
} 

enum class ErrorCodes : unsigned int {
    none = 0,
    anError,
    someOtherError
};

void foo() {
    error<ErrorCodes>(ErrorCodes::anError);
}

It should be possible to restrict the template to be an enum using enable_if and is_enum, but I can't get it compiled at the moment. It seems there are standard libraries missing for Arduino.

Please note that the default underlying type of an enum is int, not unsigned int.

Upvotes: 1

Related Questions