状态C 全局空隙函数指针

Stateful C++ global void function pointer

本文关键字:函数 指针 全局 状态      更新时间:2023-10-16

是否可以使用单个参数创建一个函数,该函数将指针返回到全球范围的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);
}