使用成员函数时的std::bind替代方案

3

我有一些需要进行基准测试的函数。我希望能够将它们传递给基准测试函数。以前,我是这样将函数指针和对象引用传递到测试函数中的:

template<typename T>
void (T::*test_fn)(int, int), T& class_obj, )

目前我有这个

#include <iostream>
#include <functional>
using namespace std::placeholders;

class aClass
{
public:
    void test(int a, int b)
    {
        std::cout << "aClass fn : " << a + b << "\n";
    }

};

class bClass
{
public:
    void test(int a, int b)
    {
        std::cout << "bClass fn : " << a * b << "\n";
    }

};

// Here I want to perform some tests on the member function
// passed in
class testing
{   
public:
    template<typename T>
    void test_me(T&& fn, int one, int two)
    {
        fn(one, two);
    }
};


int main()
{
   aClass a;
   bClass b;
   auto fn_test1 = std::bind(&aClass::test, a, _1, _2);
   auto fn_test2 = std::bind(&bClass::test, b, _1, _2);

   testing test;

   test.test_me(fn_test1, 1, 2);
   test.test_me(fn_test2, 1, 2);
}

有没有办法使用lambda来实现这个功能? 我知道可以使用std::bind来实现,但是我能否使用lambda而不必为我想要测试的每个成员函数都重复执行它(如下所示)?


你也可以使用这个:通用成员函数指针 - Samer Tufail
1个回答

5
test_me函数可以接受任何可调用对象,包括lambda表达式。不需要进行修改。
例如:
test.test_me([a](int one, int two) { a.test(one, two); }, 1, 2);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接