其他分享
首页 > 其他分享> > c – 如何在for_each方法中使用自己的类的函数?

c – 如何在for_each方法中使用自己的类的函数?

作者:互联网

假设我有这个类(继承自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();
}

如何在类本身内部使用类方法调用for_each?我知道我可以使用static关键字,但是有什么其他方法可以在不使用静态的情况下使用函数对象?

我在编译时收到此错误消息:

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);

我想我需要在某处添加.*或 – > *但我无法找到原因和原因.

解决方法:

C 11结合溶液:

std::for_each(this->begin(), this->end(),
      std::bind(&C::transformation, this, std::placeholders::_1));

C 11 lambda解决方案:

std::for_each(this->begin(), this->end(),
      [this] (T& i) { transformation(i); });

C 14通用lambda解决方案:

std::for_each(this->begin(), this->end(),
      [this] (auto&& i) { transformation(std::forward<decltype(i)>(i)); });

C 98 bind1st mem_fun解决方案:

std::for_each(this->begin(), this->end(),
      std::bind1st(std::mem_fun(&C::transformation), this));

注意:this-> begin()和this-> end()调用使用this->进行限定.只是因为在OP的代码中它们是模板化基类的成员函数.因此,这些名称是在全局命名空间中初步搜索的.任何其他此类事件都是强制性的.

标签:function-object,c,c11,foreach
来源: https://codeday.me/bug/20191007/1866448.html