mardi 24 septembre 2019

Should I use a lambda or functor for a comparison function?

I am refactoring a C++03 project to C++11.

I have a class which has a functor defined within it for sorting:

class Widget
{
public:

  class SortByRules
  {
  public:
    bool operator()(const Widget &lhs, const Widget &rhs) const;
  }
}

This functor is used in various places throughout my project. An example usage:

std::vector<Widget> widgets;

// ...

std::sort(widgets.begin(), widgets.end(), Widget::SortByRules());

As far as I understand, lambdas should be prefered to functors in C++11. But I'm not sure if I should just stick with a functor in this case because I want to call it in multiple other classes throughout my project.

I was thinking of refactoring to something like the following:

// .h
class Widget
{
public:
 Widget();
 std::function<bool(Widget&, Widget&)> SortByRules;
};

// .cpp
Widget::Widget() :
SortByRules([](Widget& lhs, Widget& rhs) { /* ... */ }
{
}

Are both of these implementations essentially the same? Should I prefer one over the other, and if so, why?

Thanks for reading!

Aucun commentaire:

Enregistrer un commentaire