int*_*ris 0 c++ lambda member-function-pointers function-pointers
我有一些需要C函数的代码,但是我想实例化一堆类实例并将该类的成员函数作为C函数传递。我需要同时捕获N个实例。我希望我可以作为lambda来做。
这是结果函数的外观(大致):
// This is the code I want to interface with:
typedef void func(ParamClass param); // ParamClass is NOT my class
extern void notMyCode1(func funcArg); // Code I want to call, saves funcArg
extern void notMyCode2() // uses saved funcArgs
// Here is the type of class I want to instantiate:
class MyClass {
public:
MyClass(int arg) : saveArg(arg) {}
int saveArg;
void myFunc(ParamClass param) {
// uses saveArg and param to do the right action
}
};
void useCase(void) {
for (int i = 0; i < max; ++i) {
MyClass myInstance(Myclass(i)); // maybe need vector to hold these?
notMyCode1(myInstance.myFunc); // this code is what I don't know how to write
}
notMyCode2();
}
Run Code Online (Sandbox Code Playgroud)
背景。我要调用的库是Google Benchmark。notMyCode1是它们的基准注册功能。notMyCode2运行已注册的基准。ParamClass是其代码传递到基准中的数据。
现在,通常情况下,一个简单的C函数传递给注册码,每个希望运行的基准都一个。但是,我想一次又一次地运行相同的代码,并用数字“ i”对其进行参数化,然后将每个“ i”都视为一个单独的基准。因此,我想在一个类中(或通过lambda捕获)“ i”,但这样会产生多个C函数指针,每个指针都绑定了“ i”的值。我尝试将“ i”作为基准的参数并传递给基准,但是基准代码将“ i”视为要求和的东西(并且我希望每个“ i”都被视为唯一的基准,并使用不同的统计参数)待计算)。
这似乎应该做起来很简单(这只是一个闭包),但是我对函数指针(或C ++ lambda)不是那么熟悉。如果这是我的代码,则只需传入类实例,但事实并非如此。
我已经在类中看到了使用静态函数的示例,但是我特别想捕获“ i”的值并获取多个函数指针,每个函数指针都捕获不同的“ i”值。
你不能。
如果lambda是无状态的(即没有捕获),则只能转换为函数指针。要从lambda调用成员函数,您需要一个指向要用来调用该成员函数的对象的指针。这将被捕获,从而使lambda对象无法转换为简单的函数指针。
您可能唯一的选择是在编译时使用模板进行索引参数化。然后返回使用类模板的简单静态函数,该函数可以作为C回调传递。
归档时间: |
|
查看次数: |
138 次 |
最近记录: |