Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/163.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 删除列表的\u if谓词_C++ - Fatal编程技术网

C++ 删除列表的\u if谓词

C++ 删除列表的\u if谓词,c++,C++,当我使用模板函数谓词时,为什么这不起作用 class A { int x; public: A(int X):x(X){} int getX() const {return x;} }; template <typename T> bool less_than_two(T const &a) { return (a.getX()<2); } int main() { list <A> l; for (in

当我使用模板函数谓词时,为什么这不起作用

class A
{
    int x;
public:
    A(int X):x(X){}
    int getX() const {return x;}
};

template <typename T>
bool less_than_two(T const &a)
{
    return (a.getX()<2);
}

int main()
{
    list <A> l;

    for (int i = 0; i < 5; i++)
        l.push_back(i);

    l.remove_if(less_than_two);
}

您需要用类型A实例化模板。因此,如果少于两个,则需要执行l.remove

小于等于2是函数模板,而不是函数。实例化它以获得一个函数,如Naveen所说。注意,当您使用小于两个{template bool operator const T&a{return a.getX的函数对象结构时,这会变得更容易