std :: all_of不接受类成员函数作为具有1个参数的函数 [英] std::all_of not accepting class member function as function with 1 argument
问题描述
我无法弄清楚这次std::all_of
通话中我在做什么.
I can't figure what I am doing wrong with this std::all_of
call.
我上了一堂统计课:
class Statistics {
public:
bool isDataSet() const { return m_data.size() > 0; }
private:
std::vector<double> m_data;
};
Statistics类的每个实例都对应于某个对象.
Each instance of Statistics class corresponds to a certain object.
在另一个文件中的另一个函数中,我仅想在全部 Statistics
实例中初始化数据后才显示统计信息.我想通过以下方式使用std::all_of
函数:
In another function in a different file I want to display statistics only if data has been initialized in all Statistics
instances. I want to use std::all_of
function in the following manner:
if( std::all_of(m_stats.begin(), m_stats.end(), &Statistics::isDataSet) ) {
...
}
其中std::vector<Statistics*> m_stats.
编译器报告错误,因为谓词项的值不等于带有1个参数的函数".据我所知,每个类成员都将此指针作为第一个参数传递,因此Statistics::isDataSet()
实际上应该是具有1个参数的函数.但是std::all_of
认为这是错误的.
The compiler reports error in that the 'predicate term does not evaluate to a function taking 1 arguments'. As far as I know, each class member passes this pointer as the first parameter, so Statistics::isDataSet()
should actually be a function with 1 parameter. But std::all_of
sees this wrong.
我认为Statistics::isDataSet()
应该作为std::all_of()
中带有1个参数的函数接受吗?
Am I wrong in my assumption that Statistics::isDataSet()
should be accepted as a function with 1 parameter in std::all_of()
?
推荐答案
使用
std::bind(&Statistics::isDataSet, std::placeholders::_1)
或
[](const Statistics& s) { return s.isDataSet(); }
调用all_of
时使用
代替&Statistics::isDataSet
.后者期望一个 callable 类型(作为谓词),并将一个Statistics
实例传递给它.指定没有实例的成员函数显然不足以拨打电话
instead of &Statistics::isDataSet
in call to all_of
. latter expect a callable type (as predicate) and will pass an instance of Statistics
to it. Specifying member-function w/o instance obviously not enough to make a call
这篇关于std :: all_of不接受类成员函数作为具有1个参数的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!