On the net I found some examples about function objects (callees) but they did not demonstrate how to use them as an argument for a callback function (which calls them, the caller) but merely the way it is used when using sort or for_each. Therefore, I made one myself:
class CBase
{
public:
virtual int operator()(int a, int b)
{
return 10;
}
};
class CSmaller: public CBase
{
public:
int operator()(int a, int b)
{
return a < b;
}
int Compute(int a, int b)
{
return a < b;
}
};
class CLarger: public CBase
{
public:
int operator()(int a, int b)
{
return a > b;
}
int Compute(int a, int b)
{
return a > b;
}
};
int caller(CBase &f, int x0, int x1)
{
return f(x0,x1);
}
int main()
{
CLarger callee1; /*this callee is being called by caller*/
CSmaller callee2; /*idem*/
int q=caller(callee1,0,1);
int z=caller(callee2,0,1);
printf("%d
",q);
printf("%d
",z);
}
这些STL功能物体(比较少)是否以这种方式得到实施(因为通常只是在使用一般名称/分类模板之前)? I.e.,这些公司(CLarger和CSmall)是否有关系/共同藏匿处,每个类别都有虚拟功能,或者它们是否也属于某些一般功能目标(只要它们执行(有两种论点的)操作者?) 与此类似(未经过测试):
template<class F>
float integrate(const F &f,float x0,float x1)
{
..f(x)..;
}
float derive(const F &f,float x0,float x1)
{
..f(x)..;
}
class CSquare
{
public:
float operator()(float x)
{
return x*x;
}
};
class CTwoX
{
public:
float operator()(float x)
{
return 2*x;
}
};
如果是正确的,如何以非STL的方式执行这些非相关的课程? 我知道,使用模板维持基本机制(以这种方式与之相关),但只有类型不同。 但是,是否需要这种关系(即,同样的追随者)?
Is using an overloaded () in a function object only meant for convenience? Because I can use CLarger s Compute as well. I can also merge those separated classes (that used virtual for their different functionality) in a class CCompute with members Larger and Smaller, for example. BTW, I think I can put derive and integrate in a class as well. Do my qeustions make sense, or do my thoughts contradict the STL theory?