c++ STL的unary_function(在gcc 4.7.x中实现)可以有虚函数吗?

Can unary_function of STL of C++ (as implemented in gcc 4.7.x) have a virtual function?

本文关键字:实现 函数 unary STL function gcc c++      更新时间:2023-10-16

binder2nd来源于unary_function

下面的代码片段不起作用:

greater<int> g;
    //greater is derived from binary_function
//bind2nd returns binder2nd object and binder2nd is derived from unary_function
const unary_function<int,bool> &greater_than_0 = bind2nd(g, 0);
    // base class reference type holding reference to derived class object
remove_if(lst.begin(), lst.end(), greater_than_0);
    //does not work

而下面的代码片段可以工作:

greater<int> g;
const binder2nd< greater<int> > &greater_than_0 = bind2nd(g, 0);
remove_if(lst.begin(), lst.end(), greater_than_0);

unary_function中有一个虚拟函数是否有帮助,以便第一个代码片段工作。这能改善STL的使用吗?

unary_function是一种方便的类型,它为派生类添加了两个类型。它是多态;如果您编写的代码在类定义中通过名称而不是作为基类提到它,那么几乎可以肯定您犯了一个错误。