| CodeGuru Home | VC++ / MFC / C++ | .NET / C# | Visual Basic | Newsletters | VB Forums | Developer.com |
|
|||||||
| Visual C++ Programming Ask questions about Windows programming with Visual C++ and help others by answering their questions. |
![]() |
|
|
Thread Tools | Search this Thread |
Rating:
|
Display Modes |
|
#1
|
|||
|
|||
|
function as a parameter for function
Hi all,
I am using Visual C++ for a long time, but I have never use it. Can somebody explain me, how to create function, which calls function, which was given as a parameter? Something like this: Code:
void MainFuncion(SecondFunction)
{
LocalFunction1();
LocalFunction2();
...
SecondFunction();
}
Thx, PetrP. PS: I think that sample code will be the best way, how to learn it. |
|
#2
|
|||
|
|||
|
Ok here ya go
#include <stdio.h> // is the function passed around void Function(int Parameter) { printf("%u",Parameter); } // Receives the function pointer and calls it void CallThisFunction(void (*FunctionPtr)(int Parameter1)) { FunctionPtr(0); } void main() { // Call the function passing the function pointer CallThisFunction(Function); } |
|
#3
|
|||
|
|||
|
or you could do something like:
template <typename fun_type> void MainFunction(fun_type SecondFunction) { SecondFunction(); } where fun_type can be both function pointers or classes with operator () overloaded. |
|
#4
|
|||
|
|||
|
Possibly, never tried it before. I'm not sure if it will work as a template. If it does it could be tricky when it comes to handling the function parameters unless you use the ... for parameter passing. I'd be interested to see if it does work.
|
|
#5
|
|||
|
|||
|
Thanks to both,
all possibilities were working fine. First one from Quintesence was working also with parameter passing, second one form amag was also working fine until I want pass the parameters. All these was working in console application. I tried it also in MFC classes and there were some problems. I have to little bit play with it. But I want to add it to the DLL so no MFC will be needed .Onece more, thanks to both. Petr P |
|
#6
|
|||
|
|||
|
To be able to pass parameters just do:
template <typename fun_type> void MainFunction(fun_type SecondFunction) { SecondFunction(10, "Hello"); } or whatever. The compiler checks that the fun_type you pass to the function matches the arguments. In this case void my_fun(int k, const char *text) { cout << k << text << endl; } and then MainFunction(my_fun); would work just fine! |
![]() |
| Bookmarks |
|
||||||
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|