My question is related to the arguments in a C++ function. Sometimes, you may expect that the one function can accept different kinds of arguments, and as far as I am considered this can be realized in two ways. One is to use the C++ new feature: function overloading (Polymorphism), and the other is to use the ‘C’ function way, which is illustrated in the following examples:
struct type0
{
int a;
};
struct type1
{
int a;
int b;
};
struct type2
{
int a;
int b;
int c;
};
void fun(int type, void *arg_structure)
{
switch (type)
{
case 0:
{
struct type0 *mytype = (struct type0 *)(arg_structure);
cout<<"a = "<<mytype->a<<endl;
break;
}
case 1:
{
struct type1 * mytype= (struct type1 *)(arg_structure);
cout<<"b = "<<mytype->b<<endl;
break;
}
case 2:
{
struct type2 *mytype = (struct type2 *)(arg_structure);
cout<<"c = "<<mytype->c<<endl;
break;
}
default:
break;
}
}
int main ()
{
struct type2 temp;
temp.a = 1;
temp.b = 2;
temp.c = 3;
fun(2,(void*)(&temp));
return 0;
}
My question is: are there other ways of obtaining a changeable function argument structure in C++?Thanks!
As you ask for ‘changeable argument structure’ and not ‘changeable argument type’, I would assume that you are asking for flexibility in terms of types AND number of arguments.
If so, you can use variadic functions:
or, if you have a compiler supporting C++11, variadic templates:
Otherwise, you can use overloading or templates, as others have already suggested.