状态C 全局空隙函数指针
Stateful C++ global void function pointer
是否可以使用单个参数创建一个函数,该函数将指针返回到全球范围的void返回无参数函数?
我从嵌入式硬件的意义上问,我正在尝试定义一系列中断服务程序以附加到数字引脚。
我的意思是一个例子:
#define MAX_BUTTONS 5
int main()
{
for (int i = 0; i < MAX_BUTTONS; i++) {
attachInterrupt(i, isrForI(i), RISING);
}
}
typedef void (*Isr)(void);
Isr isrForI(int i)
{
// Return a function of type Isr which calls handleInterrupt(i)
}
void handleInterrupt(int i)
{
// Do something with i
}
这里的问题不知道如何在isrForI
中足够通用,因为我需要它可以扩展,因此MAX_BUTTONS
可以是任何数字。
由于您在编译时知道MAX_BUTTONS
,因此您可能会使用模板来避免创建运行时函数:
#define MAX_BUTTONS 5
typedef void (*Isr)(void);
template <int N>
void handleInterrupt() { /* int i = N; */ }
template <int N>
Isr isrForI() {
return handleInterrupt<N>;
}
template <int N>
struct attach_interrupts {
static void attach() {
attachInterrupt(N, isrForI<N>(), RISING);
attach_interrupts<N - 1>::attach();
}
};
template <>
struct attach_interrupts<0> {
static void attach() {
attachInterrupt(0, isrForI<0>(), RISING);
}
};
int main() {
attach_interrupts<MAX_BUTTONS - 1>::attach();
}
与您的代码的唯一区别是,它将从MAX_BUTTONS - 1
而不是0
而不是CC_6连接到MAX_BUTTONS - 1
(但是您可以轻松适应模板)。
@storyteller在评论中提到的,如果要保留handleInterrupt(int)
,则可以简单地做:
void handleInterrupt(int i) { /* Your original handleInterrupt... */ }
template <int N>
void handleInterrupt() {
// Call the original one:
handleInterrupt(N);
}
相关文章:
- QMetaObject invokeMethod的基于函数指针的语法
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- c++r值引用应用于函数指针
- 模板函数指针和lambda
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 带有类的函数指针
- () 函子后面的括号,而不是函数指针?
- 全局作用域中函数指针的赋值
- 使用"Task"函数指针队列定义作业管理器
- 将成员函数指针作为参数传递给模板方法
- 如何创建对象函数指针C++映射?
- 匹配函数指针作为模板参数?
- 通过函数指针定义类范围之外的方法
- 存储在类中的函数指针
- C++从函数指针数组调用函数
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 整数键映射到头文件中的成员函数指针
- 从类成员函数到类 C 函数指针的转换
- 如何将内联匿名函数分配给C++函数指针
- 将字符缓冲区强制转换为函数指针