Gar
Gar

Reputation: 305

Alternative to std::bind when passing member function

I have some functions I'd like to benchmark. I would like be able to pass them into the benchmarking function. Previously I have passed a function pointer and reference to the object to the testing function like so

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

At the moment I have this

#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);
}

Is there a way I can do this using a lambda instead? I know I can do this using std::bind but can I do this using a lambda and not have to do it each time for each member function I want to test (as below)?

Upvotes: 3

Views: 341

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409176

The test_me function can take any callable object. Including lambdas. No modifications needed.

Something like

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

Upvotes: 5

Related Questions