Referring to function arguments by position?
I'm not sure I know how to ask this.
Let's say I have a function
void myFunc ( int8 foo, float bar, int whatever )
{
...
}
is there a quick way to reference a specific argument by its position?
void myFunc ( float foo, float bar, float whatever )
{
float f;
f = ARG[1]; // f now equals bar
}
something about that?
Following actions:
Thank you for your responses. Iโm probably wrong. It struck me as odd that C ++ doesn't allow this, as perl and some psuedo languages โโ(I think AutoIt in particular). As for the "why"? Just use a simple loop to go through them. I admit that under normal conditions there are many ways to achieve this, but I have tried to ensure that my worthless does not change any code outside of my little world. In other words, I have no control over the calling code. This is pushing the input down my throat and I have to manage it as best I can. So I can't just loop around before calling my function. Anyway, it was clearly a mess and there were no variables like this, so I was just duplicating the code. No big one. Thanks for the comments and interesting suggestions.
source to share
If you really feel that you want an array of parameters from values โโof the same type and not with explicitly specified parameters, you can simply pass the array as a parameter.
void myFunc ( float foo[3] )
{
float bar;
bar = foo[1];
}
This can be inefficient if your array is much longer, so using a const reference would be a better solution, e.g .:
void myFunc ( const float & foo[3] )
{
float bar;
bar = foo[1];
}
Or, like many C ++ questions on this site, the best solution is to use std :: vector
void myFunc ( const std::vector<float> & foo )
{
float bar;
bar = foo[1];
}
source to share
Maybe boost :: tuple is what you need?
#include <boost/tuple/tuple.hpp>
void myFunc ( const boost::tuple<int, float, double>& t )
{
float f;
f = boost::get<1>(t); // f now equals bar
}
int main()
{
myFunc( boost::make_tuple( 1, 2.0f, 3.0 ) );
}
This gives you static type checking and you can get the elements by their position. Tuples are part of the future standard. It can be used as std::tr1::tuple
already with some compilers.
If all arguments are of the same type, you can use std::vector
:
#include <vector>
void myFunc ( const std::vector<float>& t )
{
float f;
f = t[1]; // f now equals bar
}
int main()
{
std::vector<float> f_array;
f_array.push_back( 1.0f );
f_array.push_back( 2.0f );
f_array.push_back( 3.0f );
myFunc( f_array );
}
source to share
You can use C style variable arguments:
#include <stdarg.h>
void myFunc (int8 foo, ...)
{
va_list args;
va_start(args, foo);
float bar = va_arg(args, float);
int whatever = va_arg(args, int);
va_end(args);
}
but that means:
- You need to know in advance the parameters that will be used to call the function.
- You don't get any benefit of static type checking.
source to share