首页 > 解决方案 > 传递成员函数时替代 std::bind

问题描述

我有一些我想进行基准测试的功能。我希望能够将它们传递给基准测试功能。以前我已经将函数指针和对对象的引用传递给测试函数,就像这样

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 来做到这一点,而不必每次都为我想测试的每个成员函数都这样做(如下所示)?

标签: c++c++14

解决方案


test_me函数可以采用任何可调用对象。包括 lambda。无需修改。

就像是

test.test_me([a](int one, int two) { a.test(one, two); }, 1, 2);

推荐阅读