简体   繁体   中英

C++ ERROR about count_if: expected primary-expression before

vector<T> m;

is a private member in a template class.

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

is a private function in the same template class.

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

is a public function in the same template class.

ERROR: expected primary-expression before '>' token. Why??

isNotZero<T> is a member function, so it has an implicit first parameter for this . You need a unary functor, so you will need to use std::bind , to bind this as the first parameter.

You also need to refer to the function as &Matrix::isNotZero<T> . So,

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

and use f as the functor in count_if .

Alternatively, use a lambda:

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

isNotZero is a member function. You cannot use this like that. Use 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);} );
}

Or use std::bind .

There're two problems here.

  1. From your definition, isNotZero is not a template function, it is a member function of the template class.

    You cannot refer to a non-template function with template argument. Use int count = count_if(m.begin(), m.end(), isNotZero);

  2. isNotZero is a non-static member function. You cannot pass a member function like that.

    I think it's okay to make isNotZero as a static member function in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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