how to write a function that links other functions in C [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Lets say I have functions A, B, & C.
I would like to write a function which looks like:
Linker(A,B,C,{{0,1,0},{0,0,1},{0,0,0}});
where the arrays correspond to which element in the first list will be called. In other words, when A finishes, it starts the second element B, when B finishes it calls the third element C, when C finishes nothing is called.
Linker would then unroll into
generic preprocessing
run A
generic postprocessing
generic preprocessing
run B
generic postprocessing
generic preprocessing
run C
generic postprocessing
The idea being that this would make it easier to link functions together, and would save me some time in writing the pre and postprocessing steps. Also organization, error-proofing, understandability, etc... Is this Idea possible in C? would I need to use C++? how do I begin implementing an idea like this?
I am using stm32ide as my compiler as this code will run on an embedded device.

You could do this by setting up some "processing" class that stores pointers to your functions and the links you want to establish between them:
class processor {
private:
std::vector<void (*)()> funcs;
std::vector<std::pair<int, int>> links;
public:
void add_func(void (*func)()) { funcs.push_back(func); }
void link(int from, int to) { links.push_back({from, to}); }
void call(int indx) {
// Make the call
funcs.at(indx)();
// Call any links
for(auto it : links) {
if(it.first == indx) { call(it.second); }
}
}
};
Then to use it, you just need to add your functions and links, and then call call():
int main() {
processor p;
p.add_func(A);
p.add_func(B);
p.add_func(C);
p.link(0, 1); // A -> B
p.link(1, 2); // B -> C
p.call(0); // Call A
return 0;
}
See it in action here: https://ideone.com/M1Qj6f

If I understand you correctly you want to pass a function as a parameter to another function.
For c++ you can use function pointers.
#include <iostream>
void helloWorld()
{
std::cout << "Hello World" << std::endl;
}
int main()
{
helloWorld();
# Here we get the memory adress of the function helloWorld.
auto secondHelloWorld = &helloWorld;
# Here, an implicit converstion is going on.
auto thridHelloWorld = helloWorld;
secondHelloWorld();
thirdHelloWorld();
std::cin.get();
}
If you want to be more explicit with the types, you can write
#include <iostream>
void helloWorld()
{
std::cout << "Hello World" << std::endl;
}
int main()
{
helloWorld();
void(*secondHelloWorld)() = helloWorld;
void(*thridHelloWorld)() = helloWorld;
secondHelloWorld();
thirdHelloWorld();
std::cin.get();
}
I can not help you with how you should precisly implement this. I would need to know you requirements.
HTH

Your question should be clarified. If I understand well, you want to wrap a function, as done in a context manager. You should precise what is the signature of your functions A, B, C and how must be used {{0,1,0},{0,0,1},{0,0,0}}.
So to keep it simple, I'll assume that these three functions takes no parameter and do not return anything.
#include <stdio.h>
void context_manager(
void (*f)(),
void (*enter)(),
void (*exit)()
) {
enter();
f();
exit();
}
void my_enter() { printf("generic preprocessing\n"); }
void my_exit() { printf("generic postprocessing\n\n"); }
void a() { printf("run A\n"); }
void b() { printf("run B\n"); }
void c() { printf("run C\n"); }
void linker(void **fs, unsigned n) {
for (unsigned i = 0; i < n; i++) {
context_manager(fs[i], my_enter, my_exit);
}
}
int main() {
void * fs[] = {a, b, c};
linker(fs, sizeof(fs) / sizeof(void *));
return 0;
}
Result:
generic preprocessing
run A
generic postprocessing
generic preprocessing
run B
generic postprocessing
generic preprocessing
run C
generic postprocessing
You can obviously adapt the signature of f and linker to pass some parameter(s).

The hard part is that: Linker(A,B,C,{{0,1,0},{0,0,1},{0,0,0}}); cannot be written in C. The language lacks:
automatic processing or variable numbers of parameters for a function: you have to give a hint for the number and the function will have to guess the type
litteral multi-dimensional arrays do not exist in the language.
Said differently, I can imagine how to write something able to accept that syntax (apart from the semicolon) in Python, but not in C. Building a thing able to process a bunch of functions and chain them according to something is not a problem and can be done in C. But I cannot guess what the something should be, and how you intend to pass the functions and the something to the thing while respecting C syntax.

Assuming I understand what you're going for, and assuming all the functions have the same return type and argument lists, you could set up an array of function pointers and an array of integers to indicate which function to execute out of that list:
void A(void) { puts( "In A" ); }
void B(void) { puts( "In B" ); }
void C(void) { puts( "In C" ); }
/**
* Call each of the functions in f based on the values in seq;
* each seq[i] is treated as an index into f.
*
* A negative value in seq[i] indicates the end of the sequence.
*
* Inputs:
* f - list of functions we want to execute
* seq - specifies the order in which the functions are to be executed
*/
void Linker( void (*f[])(void), int *seq )
{
for ( int i = 0; seq[i] >= 0; i++ )
{
f[seq[i]]();
}
}
int main( void )
{
/**
* Use compound literals to set up each array.
*/
Linker( (void (*[])(void)) {A, B, C}, (int []) {0, 1, 2, 2, 1, 2, 0, 0, 0, -1} );
}
Output:
In A
In B
In C
In C
In B
In C
In A
In A
In A
If the functions have different return types, or if they have the same return types but take different parameter lists (or even the same parameter lists with different values), then this will need to be fleshed out a bit. You may need to create a C equivalent of a "functor" (basically a struct type that abstracts away the function return type and other details). But it should give you some ideas.

Related

how to call another function just once from recursive function without using the static variable? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
This is a sample program for my problem, I am using VisualStudio 2008
void abc()
{
static int i = 0;
if (i==0)
{
xyz();
i++;
}
abc();
}
The static variable retain the value one in next debug session also, thus not calling xyz(), how can I call a function just once without using static variable??
How about this:
void abc(int init)
{
if(init == 1) xyz();
abc(0);
}
int main(void) {
abc(1);
}
It has the advantage of showing clearly what is going on. You could even declare an enum:
enum INIT {FIRST_TIME, RECURSING};
and do
void abc(enum INIT init) {
if(init == FIRST_TIME) xyz();
abc(RECURSING):
}
You can see a complete example at work at http://codepad.org/7euiC5LQ
#include <stdio.h>
enum INIT {FIRST, RECURSING};
void abc(enum INIT init) {
if(init == FIRST) {
printf("first time\n");
abc(RECURSING);
}
else {
printf("last time\n");
}
}
int main(void) {
abc(FIRST);
}
In this example, the second time is the last time. Obviously you can embellish from there; usually you will want to pass a parameter to your abc function that might decrease with each call until you reach some point that says "this is the end of the recursion" (think factorials, Fibonacci, etc). In that case, passing an "invalid" parameter (e.g. -1) for the initial call would be a good solution. You still have only one parameter.
Finally - when you are using C++, you could consider overloading your function. Call it with a parameter, and you include xyz; call it without, and you don't. A bit like the abcStart of one of the other answers. But since you tagged your question both C and C++, and there was no evidence in your code that you really intended C++, I am not even going there...
You can pass a callflag to abc() function as an indication that whether to call xyz() function or not.
void abc(int callflag){
// do somwork
if(callflag)
xyz(); // xyz() willbe called when callflag = !0
// do other stuff
abc(0)
}
void abcStart(){
abc(1);
//abc(0); If you don't want to call xzy even for first time.
}
I think this is flexible call xyz() within abc() whenever you wants.
Not sure this is what you're looking for but it works
void abc(){
abc();
}
void abcStart(){
xyz();
abc();
}
int main(){
abcStart();
}
Doing this you don't need to specify any flag or use any if. You just call the "start" function of your recursion
Use a Boolean variable in the caller and pass it to the called function.
#include <stdbool.h> // C99 and latter supports.
void abc(bool flag)
{
if (flag)
{
xyz();
flag = false;
}
abc(flag);
}
int main(void) // T is return type
{
...
bool flag = true;
abc(flag);
...
}
Here's a solution which doesn't hard code it to running xyz a single time i.e. you could later trivially change it to run it an arbitrary number of times (credit to Floris whose answer I adapted):
void abc(int i)
{
if(i > 0)
{
xyz();
i--;
}
abc(i);
}
int main()
{
abc(1);
}

Algorithm for modular function performing different operations?

Sometimes I come across situations where I need to execute a set of code multiple times but with slight modifications. Consider 2 following cases:
Case 1:
A
B
C
Case 2:
A
D
C
//A, B, C, D are used to represent a set of code lines
Now there is no similarity between the lines of code in B & D so I am creating 2 different functions currently in my application.
However the size of code in B or D is very small in comparison to A or C.
I cannot create separate functions just for A & C because they use some common variables and it would be very messy to pass these variables as arguments.
So it looks like there is only a single solution to my problem.
Combine both the cases into a single function and choose between one of these cases by passing a bool as argument to this function. This however results in a very large size function to maintain.
So I am looking for some better alternatives as I am sure many people must have come across such situations.
EDIT:
consider just for the sake of simplicity a string variable myString.
A intialises it with some value.
B/D modify it according to some conditions.
C uses myString for some purpose, say write to file.
All in all there is flow of data like this:
Case 1:
A -> B -> C
Case 2:
A -> D -> C
Just that there is flow of a lot of data to separate each of these sets to different functions.
Options I can think of:
Create a class with A, B, C and D as functions.
All the common variables can be member variables of this class.
Create a class that simply stores all the common variables.
This can be passed by reference to A, B, C and D (so you would just pass a single variable).
Consider trying to refactor them so you minimize the number of common variables they use.
This can be done in addition to either of the above, or by itself.
Without knowing what exactly you are doing, I can't really tell you whether or not this is viable, but you should keep it in mind. While the above-mentioned parameter class is just a single variable, it's essentially just a wrapper for a bunch of variables - one should still attempt to minimize the amount of them.
One thing that you can do is define B and D as functor classes:
// this is a functor
struct B_add {
B_add(int x) : x_(x) {}
int operator()(int y) { return x_ + y; }
void set_x(int x) { x_ = x; }
private:
int x_;
};
struct D_mult {
D_mult(int x) : x_(x) {}
int operator()(int y) { return x_ * y; }
void set_x(int x) { x_ = x; }
private:
int x_;
};
Then inside the long_function_that_takes_either_B_or_D
template <typename F>
void long_function_that_takes_either_B_or_D(F & f)
{
A...
f.set_x(result_of_a);
int result_for_c = f(); //B or D
C...
}
Main:
int main(int argc, char **argv) {
long_function_that_takes_either_B_or_D(B_add(42));
long_function_that_takes_either_B_or_D(D_mult(24));
return 0;
}
It brakes OO design but i think you can try to arrange it into one class
#include <stdio.h>
class SimpleClass
{
public:
SimpleClass(void){}
void someFunction(void (* zprintf)(const char *) ) //zprintf is pointer to B or D functionality
{
printf("calling zprintf function\n"); //This is your A code
zprintf("hey");
printf("called zprintf function\n"); //This is your C code
}
~SimpleClass(void)
{}
};
And then use it like this :
void zprintf1(const char * str )
{
printf("i'm printing %s\n", str);
}
void zprintf2(const char * str )
{
printf("I don't want to print %s\n", str);
}
.
.
.
SimpleClass simpleClass;
simpleClass.someFunction(zprintf1);
simpleClass.someFunction(zprintf2);
It is a hack i know, but you can make it more pretty.
Use defines to generate code.
// A
if (runB)
// B
else
// D
// C

How to switch between 2 function sets in C++?

Is there a way, I can switch between 2 similar function sets (C/C++) in an effective way?
To explain better what I mean, lets say I have 2 sets of global functions like:
void a_someCoolFunction();
void a_anotherCoolFunction(int withParameters);
…
void b_someCoolFunction();
void b_anotherCoolFunction(int withParameters);
…
And I want to able to "switch" in my program at runtime which one is used. BUT: I dont want to have one if condition at every function, like:
void inline someCoolFunction(){
if(someState = A_STATE){
a_someCoolFunction();
}else{
b_someCoolFunction();
}
}
Because, I expect that every function is called a lot in my mainloop - so It would be preferable if I could do something like this (at start of my mainloop or when someState is changed):
if(someState = A_STATE){
useFunctionsOfType = a;
}else{
useFunctionsOfType = b;
}
and then simply call
useFunctionsOfType _someCoolFunction();
I hope its understandable what I mean… My Background: Im writing an App, that should be able to handle OpenGL ES 1.1 and OpenGL ES 2.0 both properly - but I dont want to write every render Method 2 times (like: renderOpenGL1() and renderOpenGL2() I would rather to write only render()). I already have similiar Methods like: glLoadIdentity(); myLoadIdentity(); … But need a way to switch between these two somehow.
Is there any way to accomplish this in an efficent way?
Several options, including (but not limited to):
Use function pointers.
Wrap them in classes, and use polymorphism.
Have two separate copies of the loop.
But please profile to ensure this is actually a problem, before you make any large changes to your code.
As the question seems to be interested in a C++ solution and no-one has spelt out the polymorphic solution (too obvious?), here goes.
Define an abstract base class with the API you require, and then implement a derived class for each supported implementation:
class OpenGLAbstract
{
public:
virtual ~OpenGLAbstract() {}
virtual void loadIdentity() = 0;
virtual void someFunction() = 0;
};
class OpenGLEs11 : public OpenGLAbstract
{
public:
virtual void loadIdentity()
{
// Call 1.1 API
}
virtual void someFunction()
{
// Call 1.1 API
}
};
class OpenGLEs20 : public OpenGLAbstract
{
public:
virtual void loadIdentity()
{
// Call 2.0 API
}
virtual void someFunction()
{
// Call 2.0 API
}
};
int main()
{
// Select the API to use:
bool want11 = true;
OpenGLAbstract* gl = 0;
if (want11)
gl = new OpenGLEs11;
else
gl = new OpenGLEs20;
// In the main loop.
gl->loadIdentity();
delete gl;
}
Note that this is exactly the sort of thing that C++ was intended for, so if can use C++ here, this is the simplest way to go.
Now a more subtle issue you might face is if your 2.0 version requires the process to load a dynamic linked library at run time with the 2.0 platform implementation. In that case just supporting the API switch is not enough (whatever the solution). Instead put each OpenGL concrete class in its own linked library and in each provide a factory function to create that class:
OpenGlAbstract* create();
Then load the desired library at run time and call the create() method to access the API.
In C (since it seems you want both C and C++) this is done with pointer to functions.
// Globals. Default to the a_ functions
void(*theCoolFunction)() = a_someCoolFunction;
void(*theOtherCoolFunction)(int) = a_anotherCoolFunction;
// In the code ...
{
...
// use the other functions
theCoolFunction = b_someCoolFunction;
theOtherCoolFunction = b_anotherCoolFunction;
...
}
You might probably want to switch those functions in groups, so you better set a array of pointers to functions and pass that array around. If you decide to do so, you might probably want to also define some macro to ease the reading:
void (*functions_a[2])();
void (*functions_b[2])();
void (**functions)() = functions_a;
....
#define theCoolFunction() functions[0]()
#define theOtherCoolFunction(x) functions[1](x)
....
// switch grooup:
functions = functions_b;
but in this case you'll lose the static check on argument types (and you have to initialize the array, of course).
I guess in C++ you will have instatiate two different objects with the same parent class and different implementation for their methods (but I'm no C++ prograammer!)
You could use functions pointers. You can read a lot about them if you google it, but briefly a function pointer stores a pointer to a function's memory address.
Function pointers can be used the same way as a funcion, but can be assigned the address of different functions, making it a somehow "dynamic" function. As an example:
typedef int (*func_t)(int);
int divide(int x) {
return x / 2;
}
int multiply(int x) {
return x * 2;
}
int main() {
func_t f = ÷
f(2); //returns 1
f = &multiply;
f(2); //returns 4
}
Something like boost::function (std::function) would fit the bill. Using your example:
#include <iostream>
#include <boost/function.hpp> //requires boost installation
#include <functional> //c++0x header
void a_coolFunction() {
std::cout << "Calling a_coolFunction()" << std::endl;
}
void a_coolFunction(int param) {
std::cout << "Calling a_coolFunction(" << param << ")" << std::endl;
}
void b_coolFunction() {
std::cout << "Calling b_coolFunction()" << std::endl;
}
void b_coolFunction(int param) {
std::cout << "Calling b_coolFunction(" << param << ")" << std::endl;
}
float mul_ints(int x, int y) {return ((float)x)*y;}
int main() {
std::function<void()> f1; //included in c++0x
boost::function<void(int)> f2; //boost, works with current c++
boost::function<float(int,int)> f3;
//casts are necessary to resolve overloaded functions
//otherwise you don't need them
f1 = static_cast<void(*)()>(a_coolFunction);
f2 = static_cast<void(*)(int)>(a_coolFunction);
f1();
f2(5);
//switching
f1 = static_cast<void(*)()>(b_coolFunction);
f2 = static_cast<void(*)(int)>(b_coolFunction);
f1();
f2(7);
//example from boost::function documentation. No cast required.
f3 = mul_ints;
std::cout << f3(5,3) << std::endl;
}
Compiled with g++-4.4.4, this outputs:
Calling a_coolFunction()
Calling a_coolFunction(5)
Calling b_coolFunction()
Calling b_coolFunction(7)
15
The biggest limitation is that the types of f1,f2, etc cannot change, so any function you assign to them must have the same signature (i.e. void(int) in the case of f2).
The simple way could be storing pointers to functions, and change them od demand.
But the better way is to use something similar to abstract factory design pattern. The nice generic implementation can be found in Loki library.
In C you would typically do this with a struct containing function pointers:
struct functiontable {
void (*someCoolFunction)(void);
void (*anotherCoolFunction)(int);
};
const struct functiontable table_a = { &a_someCoolFunction, &a_anotherCoolFunction };
const struct functiontable table_b = { &b_someCoolFunction, &b_anotherCoolFunction };
const struct functiontable *ftable = NULL;
To switch the active function table, you'd use:
ftable = &table_a;
To call the functions, you'd use:
ftable->someCoolFunction();

is it possible in C or C++ to create a function inside another?

Could someone please tell me if this is possible in C or C++?
void fun_a();
//int fun_b();
...
main(){
...
fun_a();
...
int fun_b(){
...
}
...
}
or something similar, as e.g. a class inside a function?
thanks for your replies,
Wow, I'm surprised nobody has said yes! Free functions cannot be nested, but functors and classes in general can.
void fun_a();
//int fun_b();
...
main(){
...
fun_a();
...
struct { int operator()() {
...
} } fun_b;
int q = fun_b();
...
}
You can give the functor a constructor and pass references to local variables to connect it to the local scope. Otherwise, it can access other local types and static variables. Local classes can't be arguments to templates, though.
C++ does not support nested functions, however you can use something like boost::lambda.
C — Yes for gcc as an extension.
C++ — No.
you can't create a function inside another function in C++.
You can however create a local class functor:
int foo()
{
class bar
{
public:
int operator()()
{
return 42;
}
};
bar b;
return b();
}
in C++0x you can create a lambda expression:
int foo()
{
auto bar = []()->int{return 42;};
return bar();
}
No but in C++0x you can http://en.wikipedia.org/wiki/C%2B%2B0x#Lambda_functions_and_expressions which may take another few years to fully support. The standard is not complete at the time of this writing.
-edit-
Yes
If you can use MSVC 2010. I ran the code below with success
void test()
{
[]() { cout << "Hello function\n"; }();
auto fn = [](int x) -> int { cout << "Hello function (" << x << " :))\n"; return x+1; };
auto v = fn(2);
fn(v);
}
output
Hello function
Hello function (2 :))
Hello function (3 :))
(I wrote >> c:\dev\loc\uniqueName.txt in the project working arguments section and copy pasted this result)
The term you're looking for is nested function. Neither standard C nor C++ allow nested functions, but GNU C allows it as an extension. Here is a good wikipedia article on the subject.
Clang/Apple are working on 'blocks', anonymous functions in C! :-D
^ ( void ) { printf("hello world\n"); }
info here and spec here, and ars technica has a bit on it
No, and there's at least one reason why it would complicate matters to allow it. Nested functions are typically expected to have access to the enclosing scope. This makes it so the "stack" can no longer be represented with a stack data structure. Instead a full tree is needed.
Consider the following code that does actually compile in gcc as KennyTM suggests.
#include <stdio.h>
typedef double (*retdouble)();
retdouble wrapper(double a) {
double square() { return a * a; }
return square;
}
int use_stack_frame(double b) {
return (int)b;
}
int main(int argc, char** argv) {
retdouble square = wrapper(3);
printf("expect 9 actual %f\n", square());
printf("expect 3 actual %d\n", use_stack_frame(3));
printf("expect 16 actual %f\n", wrapper(4)());
printf("expect 9 actual %f\n", square());
return 0;
}
I've placed what most people would expect to be printed, but in fact, this gets printed:
expect 9 actual 9.000000
expect 3 actual 3
expect 16 actual 16.000000
expect 9 actual 16.000000
Notice that the last line calls the "square" function, but the "a" value it accesses was modified during the wrapper(4) call. This is because a separate "stack" frame is not created for every invocation of "wrapper".
Note that these kinds of nested functions are actually quite common in other languages that support them like lisp and python (and even recent versions of Matlab). They lead to some very powerful functional programming capabilities, but they preclude the use of a stack for holding local scope frames.
void foo()
{
class local_to_foo
{
public: static void another_foo()
{ printf("whatevs"); }
};
local_to_foo::another_foo();
}
Or lambda's in C++0x.
You can nest a local class within a function, in which case the class will only be accessible to that function. You could then write your nested function as a member of the local class:
#include <iostream>
int f()
{
class G
{
public:
int operator()()
{
return 1;
}
} g;
return g();
}
int main()
{
std::cout << f() << std::endl;
}
Keep in mind, though, that you can't pass a function defined in a local class to an STL algorithm, such as sort().
int f()
{
class G
{
public:
bool operator()(int i, int j)
{
return false;
}
} g;
std::vector<int> v;
std::sort(v.begin(), v.end(), g); // Fails to compile
}
The error that you would get from gcc is "test.cpp:18: error: no matching function for call to `sort(__gnu_cxx::__normal_iterator > >, __gnu_cxx::__normal_iterator > >, f()::G&)'
"
It is not possible to declare a function within a function. You may, however, declare a function within a namespace or within a class in C++.
Not in standard C, but gcc and clang support them as an extension. See the gcc online manual.
Though C and C++ both prohibit nested functions, a few compilers support them anyway (e.g., if memory serves, gcc can, at least with the right flags). A nested functor is a lot more portable though.
No nested functions in C/C++, unfortunately.
As other answers have mentioned, standard C and C++ do not permit you to define nested functions. (Some compilers might allow it as an extension, but I can't say I've seen it used).
You can declare another function inside a function so that it can be called, but the definition of that function must exist outside the current function:
#include <stdlib.h>
#include <stdio.h>
int main( int argc, char* argv[])
{
int foo(int x);
/*
int bar(int x) { // this can't be done
return x;
}
*/
int a = 3;
printf( "%d\n", foo(a));
return 0;
}
int foo( int x)
{
return x+1;
}
A function declaration without an explicit 'linkage specifier' has an extern linkage. So while the declaration of the name foo in function main() is scoped to main(), it will link to the foo() function that is defined later in the file (or in a another file if that's where foo() is defined).

C++ Function List

I'm working on a fairly complex project, a custom encryption routine if you will (just for fun) and I've run into this issue in designing my code layout.
I have a number of functions that I want to be able to call by index. Specifically, I need to be able to call one randomly for the encrypt process, but then address that by a specific index in the decrypt process.
I was considering a classic function array, but my main concern is that a function array would be tricky to maintain, and a little ugly. (The goal is to get each function pair in a separate file, to reduce compile times and make the code easier to manage.) Does anyone have a more elegant C++ solution as an alternative to a function array? Speed isn't really an issue, I'm more worried about maintainability.
-Nicholas
What's wrong with function array?
You need to call functions by index. So they must be put into some "indexable by index" structure somehow. Array is probably the simplest structure that suits this need.
Example (typing out of my head, might not compile):
struct FunctionPair {
EncodeFunction encode;
DecodeFunction decode;
};
FunctionPair g_Functions[] = {
{ MyEncode1, MyDecode1 },
{ MySuperEncode, MySuperDecode },
{ MyTurboEncode, MyTurboDecode },
};
What is "ugly" or "hard to maintain" in the approach above?
You could write something like:
class EncryptionFunction
{
public:
virtual Foo Run(Bar input) = 0;
virtual ~MyFunction() {}
};
class SomeSpecificEncryptionFunction : public EncryptionFunction
{
// override the Run function
};
// ...
std::vector<EncryptionFunction*> functions;
// ...
functions[2]->Run(data);
You could use operator() instead of Run as the function name, if you prefer.
An object with an operator() method defined can act a lot like a function but be generally nicer to work with.
Polymorphism could do the trick: you couldf follow the strategy pattern, considering each strategy to implement one of your functions (or a pair of them).
Then create a vector of strategies, and use this one instead of the function list.
But frankly, I don't see the problem with the function array; you can easily create a typedef to ease the readability. Effectifely, you will end up with exactly the same file structure when using the strategy pattern.
// functiontype.h
typedef bool (*forwardfunction)( double*, double* );
// f1.h
#include "functiontype.h"
bool f1( double*, double* );
// f1.c
#include "functiontype.h"
#include "f1.h"
bool f1( double* p1, double* p2 ) { return false; }
// functioncontainer.c
#include "functiontype.h"
#include "f1.h"
#include "f2.h"
#include "f3.h"
forwardfunction my_functions[] = { f1, f2, f3 };
The function declaration and definitions are in separate files - compile time is ok.
The function grouping is in a separate file, having a dependency to the declarations only
You could take a look at the Boost.Signals library. I believe it has the ability to call its registered functions using an index.
Try Loki::Functor class. More info at CodeProject.com
You need to use an array of function pointers. The only catch is that all the functions have to have basically the same prototype, only the name of the function and passed argument names can vary. The return type and argument types (as well as the number of arguments and order) must be identical.
int Proto1( void );
int Proto2( void );
int Proto3( void );
int (*functinPointer[3])( void ) =
{
Proto1,
Proto2,
Proto3
};
Then you can do something like this:
int iFuncIdx = 0;
int iRetCode = functinPointer[iFuncIdx++]();
If you looked in boost::signals library, you'll see an example very nice, that is very elegant:
Suppose you have 4 functions like:
void print_sum(float x, float y)
{
std::cout << "The sum is " << x+y << std::endl;
}
void print_product(float x, float y)
{
std::cout << "The product is " << x*y << std::endl;
}
void print_difference(float x, float y)
{
std::cout << "The difference is " << x-y << std::endl;
}
void print_quotient(float x, float y)
{
std::cout << "The quotient is " << x/y << std::endl;
}
Then if you want to call them in a elegant way try:
boost::signal<void (float, float)> sig;
sig.connect(&print_sum);
sig.connect(&print_product);
sig.connect(&print_difference);
sig.connect(&print_quotient);
sig(5, 3);
And the output is:
The sum is 8
The product is 15
The difference is 2
The quotient is 1.66667