繁体   English   中英

传递成员函数时替代std :: bind

[英]Alternative to std::bind when passing member function

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

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

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

就像是

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM