I give the following example to illustrate my question:
class Abc
{
public:
int height();
int width();
int area();
};
typedef std::vector<class Abc> AbcArray;
void obtain_selected_list_based_on_area(AbcArray& objArray,
std::vector<int> &listIndexArray)
{
std::vector<int> areaArray;
for(int i=0; i<objArray.size(); i++)
areaArray.push_back(objArray[i].area());
function_select_list(areaArray,listIndexArray);
}
void obtain_selected_list_based_on_height(AbcArray& objArray,
std::vector<int> &listIndexArray)
{
std::vector<int> areaArray;
for(int i=0; i<objArray.size(); i++)
areaArray.push_back(objArray[i].height());
function_select_list(areaArray,listIndexArray);
}
void obtain_selected_list_based_on_width(AbcArray& objArray,
std::vector<int> &listIndexArray)
{
std::vector<int> areaArray;
for(int i=0; i<objArray.size(); i++)
areaArray.push_back(objArray[i].width());
function_select_list(areaArray,listIndexArray);
}
As you can see from the above code snippet, we decide to select the list based on three different criteria. In order to do that, we have to write three functions: obtain_selected_list_based_on_area
, obtain_selected_list_based_on_height
, and obtain_selected_list_based_on_width
.
I just wondering how I can simplify it.
For me there one solutions. One is to use function pointer:
void obtain_select_list(AbcArray& objArray, std::vector<int> &listSel, FUN fun)
{
std::vector<int> areaArray;
for(int i=0; i<objArray.size(); i++)
areaArray.push_back(objArray[i].width());
function_select_list(areaArray,listIndexArray);
}
However, I cannot make it work because the function pointer is pointing to the member of a class.
Do you have some ideas on how to make it work? Moreover, any other solutions for this problem?