std::for_each with class method

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • test30
    New Member
    • Apr 2010
    • 1

    std::for_each with class method

    hello,
    i am wondering how can i do it?
    Code:
    #include <stdio.h>
    #include <algorithm> //std::for_each()
    #include <list> //std::list<>
    class CL 
    {
    private: int times_printed;
    public: CL (): times_printed(0) {};
    public: void print()
    {
    printf("printed %d\n", ++times_printed);
    };
    private: std::list<int> content;
    public: void add(void)
    {
    content.push_back(1);
    content.push_back(2);
    content.push_back(3);
    }
    public: void printAll(void) 
    {
    std::for_each(content.begin(), content.end(), [b]CL::print[/b]);
    }
    };
    
    int main(int, char**) 
    {
    	CL a;
    	a.add();
    	a.printAll();
    	system("PAUSE");
    }
    i am interested in knowing what should i do to have this in-class method pointer sent to std::for_each 3rd argument?

    PS for those who will look for anwser like me: here is similar problem http://bytes.com/topic/c/answers/851...using-for_each but i do not get it, i think it is a little different from presented one in this topic.
  • newb16
    Contributor
    • Jul 2008
    • 687

    #2
    You have to implement void operator()(int x) in you class and pass an instance of it as the third argument to for_each.

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      The main point though is that you can only use a class static member function. You can not use an ordinary member function to pass to for_each because for_each has no object on which to call that function.

      Comment

      Working...