Functions with unknown parameters

Apr 13, 2013 at 6:38pm
Hey everyone,
I was wondering if it is possible to create a function with unknown parameters and different variable types. For example, an equation function that could be
1
2
3
4
equation(5 + 3 * 2) //would calculate 2 * 3 and then add 5
      

      equation(6 * 4 / 2 - 7) //would calculate 6 * 4, then divide by 2 and subtract 7. 

Of course all of the calculations would be written in the function, but I'm just wondering what the function prototype would look like.
Any help is greatly appreciated.
Apr 13, 2013 at 7:15pm
5, 3 and 2 in 5 + 3 * 2 are not parameters.
They are part of an expression.
That expression gets "solved" as 11, which becomes the actual parameter.
So in the end, your equation() function receives just one parameter with the value 11.

C and C++ let you write functions, function templates, and macros that take a variable number of parameters, but it's nasty.

It could look something like:

1
2
3
4
5
func(1);
func("hello", 2);
func('c', "hello", 0.2f);
func(1, 2, 3, "hello", 4, 5);
// ... 


... which doesn't look like what you want.
Last edited on Apr 13, 2013 at 7:17pm
Apr 13, 2013 at 7:15pm
If you do write those into code, the literal expressions are evaluated before the function is called, so you will have:
1
2
equation( 11 );
equation( 5 );

which both are happy with
void equation( int );

Compound expression is like a tree. You could have type A that evaluates 6 * 4. Type B that evaluates A / 2. Type C that evaluates B - 7. You do create the tree based on some input. The evaluation of the tree is obviously recursive.
Apr 13, 2013 at 7:44pm
Apart from overriding it might benefit you to do some string manipulation such as below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 
#include <iostream>
#include <string>

using namespace std;

void equation( string data );
string operators = "*+";

int main( void )
{
    equation("5 + 3 * 2");
    return 0;
}

void equation( string data ) {
    for( string::iterator i = data.begin(); i < data.end(); i++ )
        for( string::iterator j = operators.begin(); j < operators.end(); j++ )
            if( *i == *j )
                //calculation here
}


It's also possible to place all the operators on a stack called a stack-based-calculator. An alternative to my above example would be regular expressions: http://www.cplusplus.com/reference/regex/. I hope this helps somewhat.
Topic archived. No new replies allowed.