繁体   English   中英

有关count_if的C ++错误:预期的主表达式之前

[英]C++ ERROR about count_if: expected primary-expression before

vector<T> m;

是模板类中的私有成员。

template<class T>
bool Matrix_lt<T> :: isNotZero(T val) {
    return val != 0;
}

是同一模板类中的私有函数。

template<class T>
int Matrix_lt<T> :: calL0Norm() {
    int count = count_if(m.begin(), m.end(), isNotZero<T>);//ERROR
}

是同一模板类中的公共函数。

错误:“>”令牌之前的预期主表达式。 为什么??

isNotZero<T>是一个成员函数,所以它具有用于一个隐式的第一个参数this 您需要一元函子,因此将需要使用std::bind bind this绑定为第一个参数。

您还需要将该函数称为&Matrix::isNotZero<T> 所以,

using namespace std::placeholders;
auto f = std::function<bool(const T&)> f = std::bind(&Matrix::isNotZero<T>, 
                                                     this, _1);

并在count_if中将f用作函子。

或者,使用lambda:

int count = count_if(m.begin(), m.end(), 
                     [this](const T& val) { return this->isNotZero<T>(val);});

isNotZero是成员函数。 您不能这样使用。 使用lambda:

template<class T>
int Matrix_lt<T> :: calL0Norm() {
    int count = count_if(m.begin(), 
                         m.end(), 
                         [this](T const & val) { return this->isNotZero(v);} );
}

或使用std::bind

这里有两个问题。

  1. 根据您的定义, isNotZero不是模板函数,它是模板类的成员函数。

    您不能使用模板参数引用非模板函数。 使用int count = count_if(m.begin(), m.end(), isNotZero);

  2. isNotZero是一个非静态成员函数。 您不能通过这样的成员函数。

    我认为在这种情况下,可以将isNotZero为静态成员函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM