Reputation: 27
I am fresh with C++ and trying out different things with functions. I just encountered a problem, or rather a a reflection.
Imagine this; we have a function:
void test(int one, int two) {
if(one == 5) {
cout << "one is 5" << endl;
}
if(two == 10) {
cout << "two is 10" << endl;
}
if(one == 1 && two == 2) {
cout << "they both are 1 and 2" << endl;
}
}
And then down here we have our main function and we call test:
test(1, 8) which is fine, BUT what if I in some case just want to call test(1)
? What if I don't want to give two integers to the function, because I want it to only do stuff for int one
? I figured out that there is a workaround by simply doing test(1,NULL)
or test(NULL,10)
but this is ugly right?
There must be a way, I know that my example is bad but I hope you get my point.
Upvotes: 0
Views: 363
Reputation: 40869
If you need partial evaluation, see std::bind:
#include <iostream>
#include <functional>
using namespace std::placeholders;
int adder(int a, int b) {
return a + b;
}
int main() {
auto add_to_1 = std::bind(adder, 1, _1);
auto add_1_to = std::bind(adder, _1, 1);
std::cout << add_1_to(2) << std::endl;
std::cout << add_to_1(2) << std::endl;
return 0;
}
Upvotes: 0
Reputation: 2329
There are 2 options:
void test(int one, int two = -1) {
/* ... */
}
This gives the function a default value for two so calling test(2) would mean that the test function would operate with one = 2 and two = -1. These default can only work if there are no variables without default parameter after them in function definition.
void testA(int one, int two = -1); // OK
void testB(int one, int two = -1, int three); // ERROR
void testC(int one, int two = -1, int three = -1); // OK
Then the other option would be to overload this function. Overloading means that one function has two different definitions. There are some rules to follow when overloading function, mainly that the different overloads must be distinguishable by parameter that you feed them. So in your case the solution would be:
void test(int one) {
/* ... */
}
void test(int one, int two) {
/* ... */
}
If you have any more questions feel free to ask.
Upvotes: 0
Reputation: 234855
One way is to supply a default parameter to the second one:
void test(int one, int two = 0)
Then if you call it with just one parameter then the second parameter assumes the default value.
Another approach is to overload the function:
void test(int one)
This has the advantage that you can write specific behaviour for the case where a single parameter is passed.
Upvotes: 3
Reputation: 40897
You can't. You must supply arguments for every parameter a function has. You may not need to do so explicitly if there's a default argument, but that still provides an argument for that parameter.
Upvotes: -1