如何在for_each方法中使用自己的类的函数? [英] How to use a function of own class in for_each method?
问题描述
假设我有这个类(从std :: Vector继承,这只是一个例子)
Assume I have this class (inherited from std::Vector, it's just an example)
#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();
}
如何在类本身内部使用类方法调用for_each?我知道我可以使用static关键字,但是还有什么其他方法可以在不使用static的情况下使用功能对象呢?
How do I call for_each using class method inside class itself? I know I can use static keyword, but what is there any other way how to use a function object without using static?
在编译时出现此错误消息:
I get this error message while compiling:
for_each.cc:21:55:错误:无法将
'C :: transformation'从'void(C :: )(double)'
键入'void(C :: *)(double)'for_each(this-> begin(),
this-> end(),Transformation);
for_each.cc:21:55: error: cannot convert ‘C::transformation’ from type ‘void (C::)(double)’ to type ‘void (C::*)(double)’ for_each(this->begin(), this->end(), transformation);
我想我需要添加。*
或-> *
某个地方,但我找不到位置和原因。
I think I need to add .*
or ->*
somewhere but I can't find out where and why.
推荐答案
C ++ 11 bind 解决方案:
C++11 bind solution:
std::for_each(this->begin(), this->end(),
std::bind(&C::transformation, this, std::placeholders::_1));
C ++ 11 lambda 解决方案:
C++11 lambda solution:
std::for_each(this->begin(), this->end(),
[this] (T& i) { transformation(i); });
C ++ 14 通用lambda 解决方案:
C++14 generic lambda solution:
std::for_each(this->begin(), this->end(),
[this] (auto&& i) { transformation(std::forward<decltype(i)>(i)); });
C ++ 98 bind1st + mem_fun 解决方案:
C++98 bind1st+mem_fun solution:
std::for_each(this->begin(), this->end(),
std::bind1st(std::mem_fun(&C::transformation), this));
注意: this-> begin()
和 this-> end()
调用使用<$ c进行限定$ c> this-> 只是因为它们在OP的代码中是模板化基类的成员函数。这样,将首先在全局名称空间中搜索这些名称。 此
的任何其他出现都是强制性的。
Note: this->begin()
and this->end()
calls are qualified with this->
only because in the OP's code they are member functions of a templated base class. As such, those names are primirarily searched in a global namespace. Any other occurrence of this
is mandatory.
这篇关于如何在for_each方法中使用自己的类的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!