for_each中的类方法
class method in for_each
有一个类和事件结构:
struct Foo
{
Foo(): name("nx"), val(9) {}
string name;
int val;
};
class Base
{
public:
Base()
{
/*array.push_back(Foo());
array.push_back(Foo());
array.push_back(Foo()); //fill array Foo
array.push_back(Foo());
array.push_back(Foo());*/
}
void Define(Foo* desktop)
{
cout << desktop->name << " " << desktop->val << "n";
}
void Oblem()
{
/*for(int i = 0; i < array.size(); ++i)
{
Define(&array[i]);
}*/
for_each(array.begin(), array.end(), mem_fun_ref(&Base::Define));
}
public:
std::vector<Foo> array;
};
如何替换算法for_each上注释掉的循环?
我现在有这些错误:
- 错误:没有匹配调用'(std::mem_fun1_ref_t) (Foo&)'|
- 候选者有:_Ret std::mem_fun1_ref_t<_Ret, _Tp, _Arg>::operator()(_Tp&, _Arg) const [with _Ret = void, _Tp = Base, _Arg = Foo*]|
Base::Define
有两个参数:Foo* desktop
和一个隐式的Base* this
。您需要在Oblem
中绑定当前的this
,以获得仅接受Foo
的函数。此外,Define
应该将其参数作为Foo& desktop
(或者更好,如果是真实代码,则为Foo const& desktop
)。
使用TR1内的标准功能(或其Boost实现)的完整解决方案将是:
void Define(Foo const& desktop) const
{
cout << desktop.name << " " << desktop.val << "n";
}
void Oblem() const
{
for_each(
array.begin(), array.end()
, std::bind( &Base::Define, this, _1 )
);
}
class Base
{
public:
Base() : array(5) {}
void Define(Foo &desktop)
{
cout << desktop.name << " " << desktop.val << "n";
}
void Oblem()
{
for_each(array.begin(),array.end(),[this](Foo &f) {
Define(f);
});
// or
for_each(array.begin(),array.end(),
bind(&Base::Define,this,placeholders::_1));
}
public:
std::vector<Foo> array;
};
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 在静态库中嵌入类方法
- 如何制作一个将函数作为参数的类方法
- 从父类方法返回子类对象
- 使用用户定义的参数调用future/async并调用类方法
- 重载类方法的不明确调用
- 单独定义模板化嵌套类方法的正确语法
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- 如何访问由共享指针保存的类方法?
- 将子类方法声明为基类的友元
- 我的模板类方法返回错误类型?
- Qt将信号与另一个类方法连接
- 我无法使用C++指针指向类方法返回的 std::vector
- 如何在成为指向基类的指针后保留对子类方法的使用?
- 检查类方法中是否(此 == nullptr)
- 从基类实例调用派生类方法而不进行强制转换
- 函数从唯一代码调用正确的子类方法
- C++ - 如何在不静态的情况下将回调绑定到类方法?
- C++ |DLL / EXE - 如何从导出的类调用另一个类方法?
- 只为NOT STATIC类的EACH对象调用一次方法