相关疑难解决方法(0)

40
推荐指数
3
解决办法
2万
查看次数

何时使用std :: function而不是继承?

在某些情况下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)

c++ boost-function c++11

12
推荐指数
1
解决办法
2775
查看次数

是否有一种惯用的方法来在C++中创建委托集合?

我想在集合中存储具有类似签名的函数,以执行以下操作:

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)

c++ delegates function-pointers function-object

6
推荐指数
1
解决办法
289
查看次数

使用boost传递函数指针参数

使用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)

c++ boost boost-bind boost-function

1
推荐指数
1
解决办法
8740
查看次数