简体   繁体   中英

c++ Using multiple lambdas/binds to reference the same function/functionality

I am writing some tests for a class. I have multiple tests and each one creates its own MyObj . However, MyObj takes in a std::function<bool<T>> , and I don't want to create a lambda function with the same functionality every time I create MyObj . So instead of having this:

TEST1()
{
  MyObj<double> myobj([&](double time) -> bool 
      {
        time = myobj.doSomething();
        // ... more functionality
      });
}


TEST2()
{
  MyObj<double> myobj([&](double time) -> bool 
      {
        time = myobj.doSomething();
        // ... more functionality
      });
}

...

Rather I want to have the function defined once and reference it every time I have to create a new MyObj :

bool myFunc(double time)
{
  time myobj.doSomething();
  // ... more functionality
}

TEST1()
{
  MyObj<double> myobj([&myFunc]()); // Something like this
}

TEST2()
{
  MyObj<double> myobj(std::bind(&myFunc, myobj, std::placeholders::_1));  // Or something like this
}

So some things to note:

  • Class MyObj , all copy/reference constructors have been deleted.
  • Theres more functionality associated with myFunc which is why I don't want to repeat every time since there are numerous test cases.
  • I need a reference to the MyObj created in the actual function (myFunc).

Any help is appreciated. Thanks.

You can create regular functor:

struct Functor
{
    MyObj<double>& myobj;

    explicit Functor(MyObj<double>& myobj) : myobj(myobj) {};

    auto operator ()(double time) const -> bool 
    {
        time = myobj.doSomething();
        // ... more functionality
    }
};

With usage:

TEST1()
{
    MyObj<double> myobj(Functor(myobj));
    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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