Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

referencing a function's arguments by position?

Tags:

c++

I'm not sure I know how to ask this.

say I have a function

void myFunc ( int8 foo, float bar, int whatever )
{
...
}

is there a quick way of referencing a particular argument by its position?

void myFunc ( float foo, float bar, float whatever )
{
   float f;
   f = ARG[1]; // f now equals bar
}

something to that effect?

Follow up:

Thank you for your answers folks. I guess I'm going about it wrong. I find it odd that c++ doesn't allow for this, as perl and some psuedo languages (I'm thinking in particular of AutoIt) do. So as for "why"? Just to use a simple loop to go through them. I recognize that there are a myriad of better ways to achieve this in normal circumstances, but I was trying my darndest to not modify anyone's code outside of my little world. In other words I don't have control over the calling code. It is shoving the inputs down my throat and I have to manage them as best as possible. So I can't just loop before calling my function. Anyway, it was clearly going to be a mess and there weren't that many variables so I just duplicated code. No biggy. Thanks for the comments and interesting suggestions.

like image 839
Steven Avatar asked Nov 25 '25 23:11

Steven


2 Answers

May be 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 ) );
}

It gives you static type checking and you could get elements by its position. Tuples are part of future standard. It could be used as std::tr1::tuple already with some compilers.

If all arguments are the same type you could 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 );
}
like image 76
Kirill V. Lyadvinsky Avatar answered Nov 28 '25 17:11

Kirill V. Lyadvinsky


Not in C or C++, no.

As moonshadow suggests: what actual problem are you trying to solve?

(If you want to add an explanation, please edit your question rather than leaving a comment on this answer - more people will see your edit that way.)

like image 42
RichieHindle Avatar answered Nov 28 '25 16:11

RichieHindle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!