C ++ language function pointers and STL algorithm

I have an abstract functor class that overloads operator () and derived objects that implement it.

I have a function (part of another class) that tries to take an array of these functor classes and tries to pass a pointer to a member function in the for_each () std algorithm, here is an overview of what I do:

EDIT: I re-cleaned it and posted an old little example for clarity.

class A{
  operator()(x param)=0;
  operator()(y param)=0;
}

class B: public A{
  operator()(x param); //implemented
  operator()(y param);
}
...// and other derived classes from A

void ClassXYZ::function(A** aArr, size_t aSize)
{
  ...//some code here

  for(size_t i = 0; i< aSize; i++){

    A* x = aArr[i];
    for(v.begin(), v.end(), ...//need to pass pointer/functor to right operator() of x here

..//other code
}

I tried several ways, and I can’t figure out how to make it work, I need to use an abstract type, since I can have different derived types, but they all must implement the same operator () (param x).

for_each(), -() (param x). , , . , , .

?

+3
4

, , :

  • sizeof aArr , ( ChrisW)
  • virtual operator()()
  • , for, } ( , )

, A ( A -derived) operator() , param:

#include <iostream>
#include <algorithm>
#include <functional>

using namespace std;

typedef double param;      // Just for concreteness

class A {
public:
    virtual void operator()(param x) = 0;
};

class B : public A {
public:
    void operator()(param x) { cerr << "This is a B!  x==" << x << ".\n"; }
};

void function(A** aArr, size_t n, param theParam) {
    void (A::*sFunc)(param x) = &A::operator();
    for_each(aArr, aArr + n, bind2nd(mem_fun(sFunc), theParam));
}

int main(int argc, char** argv) {
    A* arr[] = { new B(), new B(), new B() };

    function(arr, 3, 42.69);

    delete arr[0];
    delete arr[1];
    delete arr[2];
    return 0;
}

mem_fun() 1 2 ; bind2nd() 1- , , function(), 2- . (for_each() 1 .)

: Alex Tingle, , , , function() A - . - :

void function(A** aArr, size_t n, vector<param> const& params) {
    for (size_t i = 0; i < n; ++i) {
        void (A::*sFunc)(param x) = &A::operator();
        for_each(params.begin(), params.end(), bind1st(mem_fun(sFunc), aArr[i]));
    }
}
+3

- ...

std::for_each(
  it->second.begin(),
  it->second.end(),
  std::bind1st(std::mem_fun(&A::operator()),x)
);
+4

"bar. * fn" . ( std:: tr1:: bind, boost:: bind).

+1

, , , ​​ .

Instead, I modified the code to include pure virtual functions in the base class, which will return functors for each derived class when it is implemented. I can't think of anything else that would work. But it compiles as follows.

But I'm curious if anyone has a solution to the original problem without using the pure "create functor" virtual methods in the base class.

0
source

Source: https://habr.com/ru/post/1718120/


All Articles