c++ - 将给定类型的任何枚举作为函数参数传递

标签 c++ arduino microcontroller

我正在开发一个使用 Arduino 框架的 AVR 微 Controller 项目。

我正在构建一个简单的错误跟踪系统,结构为一个类 (ErrorManager)。我已经定义了几个函数,比如

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

我想在组成这个项目的不同模块中分别定义错误代码。在每个模块中,我想定义一个 enum class包含该模块的代码,然后将它们传递给 error上面的函数:

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);
}

}

(让 errManager 成为我项目的一个模块中声明的 ErrorManager 对象)

我可以通过写 unsigned int 来实现这一点在 ???并使用 enum而不是 enum class ,但这意味着错误代码名称将在整个模块命名空间的范围内,或者至少在定义它们的整个类中,我宁愿避免这种情况。

有没有办法用 enum class 来做到这一点? ?例如,要写的东西???这意味着“将任何 Enum(带有 unsigned int,或一些 typedef ined 类型,甚至任何整数类型)作为参数”?

最佳答案

看来您需要一个模板:

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);
}

应该可以使用 enable_if 将模板限制为枚举。和 is_enum ,但我目前无法编译它。似乎 Arduino 缺少标准库。

请注意 enum 的默认基础类型是 int ,而不是 unsigned int .

关于c++ - 将给定类型的任何枚举作为函数参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60791361/

相关文章:

c++ - std::ofstream 的更快替代品

c++ - 默认移动构造函数 Visual Studio 2015

connection - Arduino Ethernet Shield 未连接到 WebServer

c++ - 无法从 raspberry pi pico ( c sdk ) 发送串行数据

c++ - 为什么在构造期间在基类中调用重写的虚函数?

c++ - 有没有办法在容器中存储不同的函数指针类型

android - 通过蓝牙串口从arduino发送数据

c++ - 如何编译一个简单的Arduino程序?

c# - 将 GUI 与微 Controller 连接

linux - 有关网络和微 Controller 的书籍?