G
goldfita
I love this place. This one problem keeps coming back to bite me.
Suppose I have the following situation (actually I do).
func1()
{
codeA
somefunc1()
codeB
}
func2()
{
codeA
somefunc2()
codeB
}
func3()
{
codeA
somefunc3()
codeB
}
I'm trying to follow the DRY school of thought and simplify this down
to one function. Sometimes I just use macros, but it's just awful.
Then I got to thinking, gee if only c had closures. Well I did some
searching, and according to wikipedia, you can simulate closures with
just a function pointer that takes a void pointer. The trouble is
those inner functions don't always take the same number of parameters.
I could make arbitrary structures to contain all the parameters into he
void pointer, but in my opinion, making single use structures to lump
arbitrary data together is worse than the macro method.
So, next I tried this.
#include <stdio.h>
void foo1(int a)
{
printf("%d \n",a);
}
void foo2(int a, int b)
{
printf("%d %d\n",a,b);
}
void do_foo(void (*foo)(), int opt)
{
if(opt == 1)
foo(5);
else if(opt == 2)
foo(5,10);
}
int main(void)
{
do_foo(&foo1,1);
do_foo(&foo2,2);
return 0;
}
I'm using opt to choose the function definition. It's a bit ugly, but
I'm ok with it. I'm just not sure if it's legal. I see lots of "don't
ever do this" when I google for unspecified function arguments.
So anyway, c gurus, what is the smart way to handle this? And what do
you think about closures in C, um, 2009 (just kidding)?
Suppose I have the following situation (actually I do).
func1()
{
codeA
somefunc1()
codeB
}
func2()
{
codeA
somefunc2()
codeB
}
func3()
{
codeA
somefunc3()
codeB
}
I'm trying to follow the DRY school of thought and simplify this down
to one function. Sometimes I just use macros, but it's just awful.
Then I got to thinking, gee if only c had closures. Well I did some
searching, and according to wikipedia, you can simulate closures with
just a function pointer that takes a void pointer. The trouble is
those inner functions don't always take the same number of parameters.
I could make arbitrary structures to contain all the parameters into he
void pointer, but in my opinion, making single use structures to lump
arbitrary data together is worse than the macro method.
So, next I tried this.
#include <stdio.h>
void foo1(int a)
{
printf("%d \n",a);
}
void foo2(int a, int b)
{
printf("%d %d\n",a,b);
}
void do_foo(void (*foo)(), int opt)
{
if(opt == 1)
foo(5);
else if(opt == 2)
foo(5,10);
}
int main(void)
{
do_foo(&foo1,1);
do_foo(&foo2,2);
return 0;
}
I'm using opt to choose the function definition. It's a bit ugly, but
I'm ok with it. I'm just not sure if it's legal. I see lots of "don't
ever do this" when I google for unspecified function arguments.
So anyway, c gurus, what is the smart way to handle this? And what do
you think about closures in C, um, 2009 (just kidding)?