ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2019-10-07 11:06:11  阅读:194  来源: 互联网

标签:function-object c c11 foreach


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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有