Baffling function pointer typedf problem

S

Swengtoo

Hi,
The following code compiles and runs great using Visual C++ 6.0:

a.cpp
-----
void A::DoSomething() {
cout << "test";
}

// notice: A::DoSomething() is *not* a static member function


b.hpp
-----
typedef void (A::*AFUNCPTR) ();

class B {
void ForAll(AFUNCPTR funcptr);
}

b.cpp
-----
void B::ForAll(AFUNCPTR funcptr) {
A *pNode = GetList().First();
while (pNode) {
(pNode->*funcptr)();
pNode = pNode->Next();
}
}

void B::DoIt() {
ForAll(A::DoSomething);
}



But using gcc 3.0.4 and 3.2.3 it produces the following error message:

b.cpp: In member function `void B::DoIt()':
b.cpp:238: no matching function for call to `B::ForAll(<unknown type>)'
b.hpp:92: candidates are: void B::ForAll(void (A::*)())
gmake: *** [b.o] Error 1

Any idea why?

Thanks in advance,
Swengtoo
 
V

Victor Bazarov

Swengtoo said:
Hi,
The following code compiles and runs great using Visual C++ 6.0:

a.cpp
-----
void A::DoSomething() {
cout << "test";
}

// notice: A::DoSomething() is *not* a static member function


b.hpp
-----
typedef void (A::*AFUNCPTR) ();

class B {
void ForAll(AFUNCPTR funcptr);
}

b.cpp
-----
void B::ForAll(AFUNCPTR funcptr) {
A *pNode = GetList().First();
while (pNode) {
(pNode->*funcptr)();
pNode = pNode->Next();
}
}

void B::DoIt() {
ForAll(A::DoSomething);

Add an ampersand before 'A::'. It's a requirement of the language:

ForAll(&A::DoSomething);
}



But using gcc 3.0.4 and 3.2.3 it produces the following error message:

b.cpp: In member function `void B::DoIt()':
b.cpp:238: no matching function for call to `B::ForAll(<unknown type>)'
b.hpp:92: candidates are: void B::ForAll(void (A::*)())
gmake: *** [b.o] Error 1

Any idea why?

See above
 
T

tom_usenet

void B::DoIt() {
ForAll(A::DoSomething);
ForAll(&A::DoSomething);

But using gcc 3.0.4 and 3.2.3 it produces the following error message:

b.cpp: In member function `void B::DoIt()':
b.cpp:238: no matching function for call to `B::ForAll(<unknown type>)'
b.hpp:92: candidates are: void B::ForAll(void (A::*)())
gmake: *** [b.o] Error 1

Any idea why?

In conforming code, you need the & when taking the address of a member
function, in contrast to an non-member function which automatically
decays to a pointer in most contexts.

Tom

C++ FAQ: http://www.parashift.com/c++-faq-lite/
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top