传递函数作为参数的最佳方法 [英] Best way to pass function as parameter
问题描述
在C ++中,有几种方法可以将函数作为参数传递,但是我想了解每个函数的优点和优点,例如,从算法中查找函数的签名:
In C++ there are several ways to pass function as parameter, but I would like to understand whats is the vantages and advantages of each one, for example, looking the signature of functions from algorithm:
template <class RandomAccessIterator, class Compare>
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
为什么std算法使用模板而不是std :: function来传递函数?
Why std algorithm uses template for pass function instead of std::function?
为什么线程不使用移动语义和算法功能?
Why thread uses move semantic and algorithms functions don't?
template <class Fn, class... Args>
explicit thread (Fn&& fn, Args&&... args);
PS:我无视C中用作函数指针的方式。
PS: I am disregarding the ways used in C as function pointers.
推荐答案
为什么std算法使用模板而不是std :: function来传递函数?
Why std algorithm uses template for pass function instead of std::function?
在C ++ 98中没有 std :: function
。一种替代方法是使用抽象的 Comparator
基类,该基类具有虚拟成员函数,而具体的比较器类将覆盖该成员,但是模板版本更为有效,因为它避免了虚拟函数的开销调度;如果 Compare
是类类型,则通常可以内联 operator()
。这也可能是反对今天使用 std :: function
的论点。
There was no std::function
in C++98. One alternative is to have an abstract Comparator
base class with a virtual member function to be overridden by concrete comparator classes, but the template version is more efficient since it avoids the overhead of virtual dispatch; if Compare
is a class type, then the operator()
can often be inlined. This would also be an argument against using std::function
today.
为什么线程使用移动语义和算法功能吗?
Why thread uses move semantic and algorithms functions don't?
在C ++ 98中也没有右值引用。
There also were no rvalue references in C++98.
很容易看到,现在我们有了右值引用并移动了语义,不允许将值移动到线程中是很愚蠢的(因为某些类型不可复制或效率不高)
It is easy to see that now that we have rvalue references and move semantics, it would be silly to not allow values to be moved into threads (since some types are not copyable or not efficiently copyable).
为什么 std :: sort
应该使用其比较器的值?请参阅为什么函数对象应该按值传递讨论。
Why should std::sort
take its comparator by value? See why function objects should be pass-by-value for discussion.
这篇关于传递函数作为参数的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!