Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"does not name a type" err when trying to use pointer to function

I want to make a sorting function with a custom comparator, and the function lies inside a class. At first I followed my lecturer's instruction, but it turned out to be wrong when it came to member function (pointer-to-member and pointer-to-function is 2 different pointers, and they can't be treated as the other). I followed the instruction showed here, but it wouldn't make any different http://www.radmangames.com/programming/how-to-use-function-pointers-in-cplusplus

Here's my code:

class llistStudent
{
public:
    void sort_list(bool (*comparator)(int &, int &));
    void swapStudent(int& positionA, int& positionB);

    bool sort_name_ascending(int& positionA, int& positionB);
    bool (llistStudent::*name_ascending)(int &, int &) = &llistStudent::method;
    name_ascending = llistStudent::sort_name_ascending;
};

And how I use it:

sort_list(sort_name_ascending);

It says:

'name_ascending' does not name a type

Where did I go wrong? Thanks! Edit: It was a typo when I was editing the code to post it here: sort_name_ascending!`

like image 506
Minh Nghĩa Avatar asked May 09 '26 11:05

Minh Nghĩa


1 Answers

There are two problems:

1) name_ascending = llistStudent::sort_name_ascending; is illegal in class definition. You cannot just slap random code in class like that. You should place it in some method, probably constuctor or make it part of declarator.
To fix this simply initialize your function pointer in declaration (C++11 and later only):

bool (llistStudent::*name_ascending)(int &, int &) = &llistStudent::sort_name_ascending;     

2) sort_list(sort_GPA_ascending); is not going to work. sort_list expect parameter of type bool (*)(int &, int &), and name_ascending has type bool (llistStudent::*)(int &, int &)

To fix this we need to know if your sorting function should have access to the class internals. If it should not (as it appears from your usecase), you should make it static and adjust pointer type accordingly:

static bool sort_name_ascending(int& positionA, int& positionB);
bool (*name_ascending)(int &, int &) = &llistStudent::sort_name_ascending; 

Otherwise, you need to change type of sort_list argument to bool (llistStudent::*)(int &, int &). Notice that member function pointers should be called on class instance (in your case it is probably *this).

like image 107
Revolver_Ocelot Avatar answered May 12 '26 04:05

Revolver_Ocelot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!