gpt4 book ai didi

c++ - 将类方法作为 void 函数指针传递 (C++11)

转载 作者:行者123 更新时间:2023-11-28 01:27:01 24 4
gpt4 key购买 nike

我有一个对象需要与现有的 C api 接口(interface)以注册一个中断(不带参数的 void 函数)。我可以将中断附加到函数 function() .但是,我希望能够将参数传递给函数,但这会改变函数签名。我想到了一种解决方法是创建一个对象来存储参数(并根据需要修改它们),然后传入一个方法(或类似方法)。但是,我一直无法弄清楚该怎么做。

我尝试将 lambda 作为 [=](){ std::cout << "a: " << a << "\n"; } 传递, 但事实证明带有捕获的 lambda 不能转换为函数指针。我也尝试过模板化方法(因为它会在编译时实例化),但无法让它工作。我在 SO 上看到过一些关于 std::bind 的帖子和 std::function ,但他们经常警告虚函数开销,我想在 ISR 的嵌入式平台上避免这种情况。

将参数化函数转换为 void(*)() 的最佳方法是什么? ?

#include <iostream>

void function() {
std::cout << "Hello World!\n";
}

void attach_interrupt(void(*fn)()) {
fn();
}

class A {
int a;

public:
A(int a) : a(a) {
attach_interrupt(function); // This works as expected
// attach_interrupt(method); // How do I make this work?
// attach_interrupt(method2<a>);
}

void method() {
// something requiring a and b
std::cout << "a: " << a << "\n";
}

template<int a>
void method2() {
std::cout << "a: " << a << "\n";
}
};

int main()
{
const int PIN_1 = 0;
const int PIN_2 = 1;
const int PIN_3 = 2;

A foo(PIN_1);
A bar(PIN_2);
A baz(PIN_3);

return 0;
}

编辑:我的解决方案,灵感来自所选答案:

#include <iostream>

void attach_interrupt(int pin, void(*fn)()) {
fn();
}

// Free function, which works as an ISR
template <unsigned int IRQ, unsigned int IRQ2>
static void irqHandler()
{
std::cout << "IRQ: " << IRQ << "\n";
std::cout << "IRQ2: " << IRQ2 << "\n";
};

template <unsigned int PIN_1, unsigned int PIN_2>
class Handler {
private:

public:
Handler() {
void(*irq)() = &irqHandler<PIN_1, PIN_2>;
attach_interrupt(0, irq);
attach_interrupt(0, &handler_2);
}

// static member function can have its address taken, also works as ISR
static void handler_2() {
std::cout << "PIN_1: " << PIN_1 << "\n";
std::cout << "PIN_2: " << PIN_2 << "\n";
}
};

Handler<1, 2> a;
Handler<2, 3> b;

int main()
{
return 0;
}

最佳答案

所以你想为不同的中断注册一个相同的中断处理程序,每个中断处理程序具有相同但独立的数据...

带有静态数据的独立模板函数怎么样?

template <unsigned int IRQ>
void irqHandler()
{
static A a(IRQ);
a.doSomething();
};

void(*interruptVectorTable[12])() =
{
// ...
&irqHandler<7>,
// ...
&irqHandler<10>,
};

关于c++ - 将类方法作为 void 函数指针传递 (C++11),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53310769/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com