如何为每个循环传递成员函数? [英] How to pass a member function in for each loop?

查看:73
本文介绍了如何为每个循环传递成员函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 std :: for_each()代替常规的 for 循环,但是我无法将成员函数传递给 for_each().

I'm trying to use std::for_each() instead of a normal for loop as a practice, but I can't pass a member function to for_each().

这是代码:

class Class
{
    public :
        void func (int a)
        {
            cout << a * 3 << " ";
        }
}ob1;

int main()
{
    int arr[5] = { 1, 5, 2, 4, 3 };
    cout << "Multiple of 3 of elements are : ";
    for_each(arr, arr + 5, ob1);
}

仅当此成员函数为 void operator()(int a)时,此方法才有效.我不知道为什么其他任何成员函数都不能传递到 for_each()

It works only if this member function is void operator() (int a). I don't know why any other member function cannot be passed into for_each()!

推荐答案

您没有将任何类方法传递给 for_each(),而是传递了一个对象,该对象仅在该对象实现 operator().

You are not passing any class method to for_each(), you are passing an object, which only works when the object implements operator().

要让 for_each()调用您的 Class :: func()方法,您需要:

To let for_each() call your Class::func() method, you would need to either:

  • 在您的课程中实现 operator():

class Class
{
public:
    void func (int a)
    {
        std::cout << a * 3 << " ";
    }

    void operator()(int a)
    {
        func(a);
    }
}ob1;

std::for_each(arr, arr + 5, ob1);

  • 使用实现 operator()的单独委托来调用您的类.

  • use a separate delegate that implements operator() to call into your class.

    • 您可以定义自定义函子(C ++ 11之前的版本):

    • you can define a custom functor (pre-C++11):

    struct functor
    {
        Class &obj;
    
        functor(Class &c) : obj(c) {}
    
        void operator()(int a)
        {
            obj.func(a);
        }
    };
    
    std::for_each(arr, arr + 5, functor(ob1));
    

  • 或使用 std :: bind() (C ++ 11和更高版本):

  • or use std::bind() (C++11 and later):

    #include <functional>
    
    auto func = std::bind(&Class::func, &obj1, std::placeholders::_1);
    std::for_each(arr, arr + 5, func);
    

  • 或使用 lambda (C ++ 11和稍后):

  • or use a lambda (C++11 and later):

    auto func = [&](int a){ obj1.func(a); };
    std::for_each(arr, arr + 5, func);
    

  • 这篇关于如何为每个循环传递成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆