Mic*_*ndr 2 c++ foreach function-object c++11
假设我有这个类(继承自std :: Vector,它只是一个例子)
#include <vector>
using namespace std;
template <class T>
class C : public vector<T> {
// I don't want to use static keyword
void transformation(T i) {
i *= 100;
}
public:
void method() {
for_each(this->begin(), this->end(), transformation);
}
};
int main() {
C<double> c;
for (int i=-3; i<4; ++i) {
c.push_back(i);
}
c.method();
}
Run Code Online (Sandbox Code Playgroud)
如何在类本身内部使用类方法调用for_each?我知道我可以使用static关键字,但是有什么其他方法可以在不使用静态的情况下使用函数对象?
我在编译时收到此错误消息:
for_each.cc:21:55:错误:无法将'C :: transformation'从类型'void(C ::)(double)'转换为'void(C ::*)(double)'for_each(this-> begin(),this-> end(),transformation);
我想我需要添加.*或在->*某处,但我找不到在哪里以及为什么.
Pio*_*cki 14
C++ 11 绑定解决方案:
std::for_each(this->begin(), this->end(),
std::bind(&C::transformation, this, std::placeholders::_1));
Run Code Online (Sandbox Code Playgroud)
C++ 11 lambda解决方案:
std::for_each(this->begin(), this->end(),
[this] (T& i) { transformation(i); });
Run Code Online (Sandbox Code Playgroud)
C++ 14 通用lambda解决方案:
std::for_each(this->begin(), this->end(),
[this] (auto&& i) { transformation(std::forward<decltype(i)>(i)); });
Run Code Online (Sandbox Code Playgroud)
C++ 98 bind1st + mem_fun解决方案:
std::for_each(this->begin(), this->end(),
std::bind1st(std::mem_fun(&C::transformation), this));
Run Code Online (Sandbox Code Playgroud)
注意: this->begin()并且this->end()调用this->仅限于因为在OP的代码中它们是模板化基类的成员函数.因此,这些名称是在全局命名空间中初步搜索的.任何其他事件this都是强制性的.