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是一种便捷类型,它为派生类添加了两个typedef。它不是多态的;如果您编写的代码在类定义中作为基类以外的名称来提及它,则几乎肯定会犯错。

08-07 02:53