c ++ pass成员函数

问题描述 投票:1回答:2

我正在尝试创建一个可以多次运行函数的类,并告诉我该函数执行所需的平均时间。

我的解决方案使用

template<class T_ret = void, class ... T_args>
void RunNewTiming(string outputFileName, T_ret(*function)(T_args ...), int iterations = 1, T_args ... otherArgs);

它适用于这样的全局函数

void foo(){
    // code
}

bool bar(int & a, char b){
    // more code
}

FunctionTimer functionTimer;

functionTimer.RunNewTiming("TimingForFoo", &foo, 1000);

functionTimer.RunNewTiming<bool, int , char>("TimingForBar", &bar, 1000, 5, 'h');

但是,如果我尝试传递类似对象的公共函数,则>

class Object{
public:
    void func(){
        // code
    };
}

Object obj;

functionTimer("TimingForObjFunc", obj.func, 1000);

我收到错误

指向绑定函数的指针只能用于调用该函数

[我尝试查找此错误的任何地方,只会使人们在尝试调用函数时无意中错过了(),并且人们指出他们无意中错过了()作为解决方案,我找不到在此上下文。

是否可以通过这样的非静态成员函数?还是有更深层的原因导致此功能不起作用

我正在尝试创建一个可以多次运行某个函数的类,并告诉我该函数执行所需的平均时间。我的解决方案使用template

c++ function-pointers
2个回答
1
投票

更新:


1
投票

我也提出以下解决方案:

© www.soinside.com 2019 - 2024. All rights reserved.