假設我有這個類(STD從繼承:: vector的,這只是一個例子)如何在for_each方法中使用自己的類的函數?
#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使用內部類本身類的方法?我知道我可以使用靜態關鍵字,但有什麼其他方式如何使用函數對象而不使用靜態?
我收到此錯誤信息在編譯:
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);
我想我需要添加.*
或->*
的地方,但我不能找出爲什麼。
嗯,我想我在這裏找到了一個解決方案:http://stackoverflow.com/questions/18006685/call-a-member-function-using-for-each – 2014-09-29 11:41:17
lambda解決方案呢?(this-> begin(),this-> end(),[this](T&ob){transformation(ob);}); – 2014-09-29 11:42:22
您可能想要'void transformation(T & i);',而不是'void transformation(T i);'。 – aschepler 2014-09-29 11:44:13