std::function<T1(T2)>比原版有T1 (*)(T2)什么优势?
在某些情况下std::function可以取代继承.以下两个代码片段非常相似(调用函数时的成本大致相同,签名中的用法几乎相同,在大多数情况下,std :: function也不需要我们制作额外的副本A):
struct Function
{
virtual int operator()( int ) const =0;
};
struct A
: public Function
{
int operator()( int x ) const override { return x; }
};
Run Code Online (Sandbox Code Playgroud)
使用std::function,我们可以重写为
using Function = std::function<int (int)>;
struct A
{
int operator()( int x ) const { return x; }
};
Run Code Online (Sandbox Code Playgroud)
为了更清楚,两个片段是如何相关的:它们都可以通过以下方式使用:
int anotherFunction( Function const& f, int x ) { return f( x ) + f( x ); }
int main( int …Run Code Online (Sandbox Code Playgroud) 我想在集合中存储具有类似签名的函数,以执行以下操作:
f(vector<Order>& orders, vector<Function>& functions) {
foreach(process_orders in functions) process_orders(orders);
}
Run Code Online (Sandbox Code Playgroud)
我想到了函数指针:
void GiveCoolOrdersToBob(Order);
void GiveStupidOrdersToJohn(Order);
typedef void (*Function)(Order);
vector<Function> functions;
functions.push_back(&GiveStupidOrdersToJohn);
functions.push_back(&GiveCoolOrdersToBob);
Run Code Online (Sandbox Code Playgroud)
或多态函数对象:
struct IOrderFunction {
virtual void operator()(Order) = 0;
}
struct GiveCoolOrdersToBob : IOrderFunction {
...
}
struct GiveStupidOrdersToJohn : IOrderFunction {
...
}
vector<IOrderFunction*> functions;
functions.push_back(new GiveStupidOrdersToJohn());
functions.push_back(new GiveCoolOrdersToBob());
Run Code Online (Sandbox Code Playgroud) 使用boost :: function和/或boost :: bind可以简化/改进以下函数指针传递吗?
void PassPtr(int (*pt2Func)(float, std::string, std::string))
{
int result = (*pt2Func)(12, "a", "b"); // call using function pointer
cout << result << endl;
}
// execute example code
void Pass_A_Function_Pointer()
{
PassPtr(&DoIt);
}
Run Code Online (Sandbox Code Playgroud)