Domanda

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??

È stato utile?

Soluzione

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);});

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top