When are stateless class functors useful in place of a c style function?

若如初见. 提交于 2020-01-21 04:50:12

问题


I've found some good examples of functors on SO like this one, and all the convincing examples seem to use state in the class that defines operator().

I came across an example in a book that defines the function call operator without having state, and I can't help but feel like this is an awkward usage, and that a normal style function pointer, would be better than using operator() in every way here - less code, less variables (you have to instantiate the comparators), its probably more efficient due to the instantiation, and no loss of meaning or encapsulation (since it's just one function).

I know std::sort lets you pick between operator() classes and functions, but I've always just used the functions because of the above logic.

What are the reasons why a class might be preferred?

Here's the example (paraphrased):

class Point2D {
   //.. accessors, constructors
   int x,y;
};
class HorizComp {
public:
   bool operator()(const Point2D& p, const Point2D& q) const
   { return p.getX() < q.getX(); }
};

class VertComp {
public:
   bool operator()(const Point2D& p, const Point2D& q) const
   { return p.getY() < q.getY(); }
};

template <typename E, typename C>
void printSmaller(const E& p, const E& q, const C& isLess) {
   cout << (isLess(p, q) ? p : q) << endl; // print the smaller of p and q
}
//...
// usage in some function:
Point2D p(1.2, 3.2), q(1.5, 9.2);
HorizComp horizComp;
VertComp vorizComp;
printSmaller(p, q, horizComp);
printSmaller(p, q, vorizComp);

回答1:


The typical reason is that when you do this:

bool less_than(const Point&, const Point&);
// ...
std::sort(..., &less_than);

The template argument for the predicate is the following:

bool(const Point&,const Point&)

Since the sort function receives a function pointer, it is more difficult for the compiler to inline the predicate use inside std::sort(). This happens because you could have another function

bool greater_than(const Point&, const Point&);

which has the exact same type, meaning the std::sort() instatiation would be shared between the two predicates. (remember that I said that it makes inlining more difficult, not impossible).

In contrast, when you do this:

struct less_than {
    bool operator()(const Point&, const Point&) const;
};
// ...
std::sort(..., less_than());


struct greater_than {
    bool operator()(const Point&, const Point&) const;
};
// ...
std::sort(..., greater_than());

The compiler generates a unique template instantiation for std::sort() for each predicate, making it easier to inline the predicate's definition.




回答2:


One reason is run-time efficiency. If you pass a pointer to a function, the compiler has to be unusually clever to produce code for that function inline. Passing an object that defines operator() makes it much easier for the compiler to produce the code inline. Especially for something like sorting, this can increase speed quite substantially.

In C++11, another reason to use a class is for convenience -- you can use a lambda expression to define the class.




回答3:


Others have made good points about the ability for the compiler to inline the functor. One other possibile advantage of functor objects vs. function pointers is flexibility. The functor might be a template, maybe a derived class, perhaps it has run time configuration (even if stateless at the time operator() is called etc.




回答4:


Another reason is that sometimes one comparison function is not enough. Let's say we have a vector of pointers:

struct X { string name; };
vector<shared_ptr<X>> v;

Now if we want to sort the vector by name, we have to define our own predicate for the sort function:

struct Cmp1
{
    bool operator()(const shared_ptr<X>& left, const shared_ptr<X>& right) const
    { return left->name < right->name; }
};

That's cool, but what do we do when we need to find the objects with specific name? To work with equal_range, the predicate needs to have two different comparison functions:

struct Cmp2
{
    bool operator()(const shared_ptr<X>& left, const string& right) const
    { return left->name < right; }

    bool operator()(const string& left, const shared_ptr<X>& right) const
    { return left < right->name; }
};

This allows us to call equal_range with a string name object:

equal_range(v.begin(), v.end(), name, Cmp2())



回答5:


In template libraries where the state of functor argument is not known at definition time, argument of class type provides a more generic interface than none-instance function pointers. STL is a great example where the statefull or stateless perdicates and functors can be used as parameters to classes and functions. If template programming is not part of the plan, function pointer is superior to stateless functor class; a single instance of function can accept all function pointers of a specific signature and code size is minimized. But in case there is a minimal probability of future library extension, functor makes it more generic.



来源:https://stackoverflow.com/questions/9288694/when-are-stateless-class-functors-useful-in-place-of-a-c-style-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!