Thursday, March 24, 2011

Using std::for_each on polymorphic method in c++

When using the std::for_each,

class A;
vector<A*> VectorOfAPointers;

std::for_each(VectorOfAPointers.begin(), VectorOfAPointers.end(), std::mem_fun(&A::foo));

If we have classes inheriting from A and implementing foo(), and we hold a vector of pointers to A, is there any way to call a polymorphic call on foo(), rather then explicitly calling A::foo()? Note: I can't use boost, only standard STL.

Thanks, Gal

From stackoverflow
  • It actually works this way.

    #include <algorithm>
    #include <iostream>
    #include <functional>
    #include <vector>
    
    struct A {
        virtual void foo() {
         std::cout << "A::foo()" << std::endl;
        }
    };
    struct B: public A {
        virtual void foo() {
         std::cout << "B::foo()" << std::endl;
        }
    };
    
    int main()
    {
        std::vector<A*> VectorOfAPointers;
        VectorOfAPointers.push_back(new B());
        std::for_each(VectorOfAPointers.begin(), VectorOfAPointers.end(), std::mem_fun(&A::foo));
        return 0;
    }
    

    prints

    B::foo()
    

    So it does exactly what you want. Check that virtual keywords are present though, it's easy to forget them.

0 comments:

Post a Comment