关于 count_if : expected primary-expression before 的 C++ 错误

标签 c++ oop templates stl stl-algorithm

vector<T> m;

是模板类中的私有(private)成员。

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

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

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

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

错误:“>”标记之前应有主表达式。 为什么??

最佳答案

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

并使用f作为 count_if 中的仿函数.

或者,使用 lambda:

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

关于关于 count_if : expected primary-expression before 的 C++ 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22980867/

相关文章:

C++ []运算符重载问题

c++ - 用 decltype 解释这段代码

java - 可序列化类中的不可序列化字段(transient 关键字)

c++ - 模板继承 - 分配失败

Css div 模板

c++ - 视觉检漏仪输出分析 : not able to decode what the result on output screen means

c++ - 为什么要发明 wchar_t?

php - 保护独立变量

php - PDO MySQL `prepared statements` 使用或不使用占位符

c++ - 在调用者方法中衰减多个函数