C
carvalho.miguel
hello,
imagine you have a static class method that receives a function
pointer, an int with the number of arguments and a variable number of
arguments.
in that static method you want to call that function (using its
pointer) and call it with the same argument list that was passed into
the static method.
sorry the bad explanation, maybe the code will make it clearer:
#include <iostream>
#include <stdarg.h>
//just a function to sum a variable number of integers
int Sum(int num, ...)
{
int res = 0;
va_list arguments;
va_start(arguments, num);
for(int i = 0; i < num; i++)
{
res += va_arg(arguments, int);
}
return res;
}
//just a function to sub a variable number of integers
int Sub(int num, ...)
{
int res = 0;
va_list arguments;
va_start(arguments, num);
for(int i = 0; i < num; i++)
{
res -= va_arg(arguments, int);
}
return res;
}
class Operation
{
public:
static int Calc(int (*op)(int num, ...), int num, ...)
{
//here is where the problem exists, how can i pass that argument
list to the op function?
return (*op)(num, ...);//ofc this gives me a syntax error.
}
};
int main(int argc, char *argv[])
{
//usage example
std::cout << Operation::Calc(Sum, 3, 1, 2, 3) << std::endl;//should
print 6 (1+2+3)
return 0;
}
thanks in advance
imagine you have a static class method that receives a function
pointer, an int with the number of arguments and a variable number of
arguments.
in that static method you want to call that function (using its
pointer) and call it with the same argument list that was passed into
the static method.
sorry the bad explanation, maybe the code will make it clearer:
#include <iostream>
#include <stdarg.h>
//just a function to sum a variable number of integers
int Sum(int num, ...)
{
int res = 0;
va_list arguments;
va_start(arguments, num);
for(int i = 0; i < num; i++)
{
res += va_arg(arguments, int);
}
return res;
}
//just a function to sub a variable number of integers
int Sub(int num, ...)
{
int res = 0;
va_list arguments;
va_start(arguments, num);
for(int i = 0; i < num; i++)
{
res -= va_arg(arguments, int);
}
return res;
}
class Operation
{
public:
static int Calc(int (*op)(int num, ...), int num, ...)
{
//here is where the problem exists, how can i pass that argument
list to the op function?
return (*op)(num, ...);//ofc this gives me a syntax error.
}
};
int main(int argc, char *argv[])
{
//usage example
std::cout << Operation::Calc(Sum, 3, 1, 2, 3) << std::endl;//should
print 6 (1+2+3)
return 0;
}
thanks in advance