std::for_each usage on member function with two args

瘦欲@ 提交于 2020-01-01 05:41:10

问题


Here's a general idea of how my class is defined as ( it performs other operations than what is mentioned below)

struct Funktor
{
    Funktor(int val):m_val(val){}
    bool operator()(int arg1, int arg2) { return m_val==arg1*arg2; }
    int m_val;
};

And now I have a vector of the above objects, and I am trying to call operator() using for_each, is there a way to do this? I know it can be done using bind2nd and mem_func_ref but when there's only one argument but for two arguments I haven't found a way.

int main()
{
    std::vector<Funktor> funktors;
    funktors.push_back(Funktor(10));
    funktors.push_back(Funktor(20));
    funktors.push_back(Funktor(30));

    int arg1 = 5, arg2 = 6;
    //instead of the for loop below I want to use for_each
    for(std::vector<Funktor>::iterator itr = funktors.begin(); funktors.end() != itr; ++itr)
    {
        (*itr)(arg1,arg2);
   }
}

Thanks for any help. Best.

CV


回答1:


C++03 Solution (without boost):

Write another functor as:

struct TwoArgFunctor
{
    int arg1, arg2;
    TwoArgFunctor(int a, int b) :arg1(a), arg2(b) {}

    template<typename Functor>
    bool operator()(Functor fun)
    {
        return fun(arg1, arg2); //here you invoke the actual functor!
    }
};

Then use it as:

std::for_each(funktors.begin(),funktors.end(), TwoArgFunctor(arg1,arg2));

C++11 Solution:

std::for_each(funktors.begin(),funktors.end(), 
                         [&] (Funktor f) -> bool { return f(arg1,arg2); });


来源:https://stackoverflow.com/questions/7393056/stdfor-each-usage-on-member-function-with-two-args

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!