C++ question...

C++ question...

Post by Desoxena on Mon Feb 21, 2011 6:11 pm
([msg=54017]see C++ question...[/msg])

So I have been getting into openGL(C++) lately, and was wondering, can you put functions into an array?
example:

funcArray(main(), Initialize(), Draw());
Can you do this? And if so, how?
and if not, what are equivalent/better alternatives?
thanks! :D
Desoxena
New User
New User
 
Posts: 25
Joined: Sun Oct 03, 2010 7:13 pm
Blog: View Blog (0)


Re: C++ question...

Post by Assassian360 on Mon Feb 21, 2011 7:29 pm
([msg=54019]see Re: C++ question...[/msg])

I would say that typically it would be impractical to do this. Particularly since then knowing what functions should be taking what parameters if they need parameters can be complex. That isn't even considering how annoying to debug or read your code it could make it.

It is actually possible to create an array of pointers to functions and dereference and call those functions with parameters. See this following link if you are interested: http://www.newty.de/fpt/fpt.html
A quick search on google brought that straight out.

There are various different ways of doing the types of things you are wanting with the calling of different functions at different times. What exactly are you wanting to achieve by putting the function calls into an array as opposed to using a switch or IF statement?
Assassian360
Poster
Poster
 
Posts: 135
Joined: Sat Jun 26, 2010 1:37 am
Blog: View Blog (0)


Re: C++ question...

Post by thetan on Sat Feb 26, 2011 6:32 pm
([msg=54362]see Re: C++ question...[/msg])

It's actually a really practical design pattern and it's known as a jump table. It's more of a common design pattern in purely functional languages like Haskel and Lisp and a equally powerful design pattern highly used in lesser functional languages like Javascript, Python and Ruby (no, C is not a functional language and neither is C++, the prior is a procedural language with the latter being an OOP/procedural language)

However the rest of your concerns in large remain valid. As part of the design pattern all the possible functions _should_ take all the same arguemnts.

FYI: i emphasize should because it's language dependent wether it should or shouldn't but in C/C++ they have to take the same arguments.

All you do is create an array of function pointers and populate the array with pointers to functions you will want to call. You can then pass then call them by offset

You can see a running example i wrote up in 5 seconds here: http://codepad.org/r6x6VD4o
"If art interprets our dreams, the computer executes them in the guise of programs!" - SICP

Image

“If at first, the idea is not absurd, then there is no hope for it” - Albert Einstein
User avatar
thetan
Contributor
Contributor
 
Posts: 657
Joined: Thu Dec 17, 2009 6:58 pm
Location: Various Bay Area Cities, California
Blog: View Blog (0)



Return to C and C++

Who is online

Users browsing this forum: No registered users and 0 guests