+ Reply to Thread
Results 1 to 2 of 2

Thread: How to create function table using stl container?

  1. #1
    Junior Member
    Join Date
    May 2012
    Posts
    27

    How to create function table using stl container?

    I have following code:

    Code:
    void UseSelect(int nData)
    {
    	switch(nData)
    	{
    	case 0:
    		{
    			Function1(nData) ;
    		}
    		break ;
    	case 1:
    		{
    			Function2(nData) ;
    		}
    		break ;
    		//etc...
    	}
    }
    I want to improve this and want to avoid more duplicate codes.

    How can I do this using stl container classes?

  2. #2
    Use following approach:

    Code:
    typedef void (*PFNFUNCTIONPOINTER) (int) ;
    
    std::map<int, PFNFUNCTIONPOINTER> myFunctionTable ;
    
    void Function1(int nData)
    {
    }
    
    void Function2(int nData)
    {
    }
    
    void BuildFunctionTable()
    {
    	myFunctionTable[0] = &Function1 ;
    	myFunctionTable[1] = &Function2 ;
    }
    
    void ExecuteFunction(int nData)
    {
    	std::map<int, PFNFUNCTIONPOINTER>::iterator itr = myFunctionTable.find(nData) ;
    	if (itr != myFunctionTable.end())
    	{
    		PFNFUNCTIONPOINTER pMyFunction = itr->second ;
    		pMyFunction(nData) ;
    	}
    }
    
    void UseFunctionTable()
    {
          BuildFunctionTable() ;
    
          ExecuteFunction(0) ;
    
          ExecuteFunction(1) ;  
    }

+ 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