+ Reply to Thread
Results 1 to 2 of 2

Thread: What is mem_func in C++?

  1. #1

    What is mem_func in C++?

    What is mem_func in C++? How to use it?

    Provide some example.

  2. #2
    Sometimes it is useful to use class member function as a function object.

    Whenever you have container of pointer of a type then you can use this scheme.

    Example:

    Code:
    class CStudent
    {
    private:
    	int m_nRoleID ;
    public:
    	CStudent()
    	{
    		m_nRoleID = 0 ;
    	}
    
    	~CStudent()
    	{
    	}
    	
    	CStudent(int nRoleID)
    	{
    		m_nRoleID = nRoleID ;
    	}
    
    	bool DisplayRoleID()
    	{
    		char szMessage[100] ;
    		sprintf(szMessage, "RoleID= %d\n", m_nRoleID) ;
    		OutputDebugString(szMessage) ;
    		return true ;
    	}
    } ;
    
    void UseMemFunc()
    {
    	std::vector<CStudent *> aStudents ;
    	aStudents.push_back(new CStudent(1)) ;
    	aStudents.push_back(new CStudent(2)) ;
    	aStudents.push_back(new CStudent(3)) ;
    
    	std::for_each(aStudents.begin(), aStudents.end(), std::mem_fun<bool, CStudent>(&CStudent::DisplayRoleID)) ;
    }
    In above example, CStudent:isplayRoleID will be called for each item in the aStudents array.

+ Reply to Thread

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts