Reputation: 1405
I really like the functools.partial
function in python and the idea of this functionallity in general. As example consider the following python script (I know that this case is not a very usefull example für using functools.partial, it should just be an easy example.)
import functools
def func(a, b, c):
sum = a + b + c
return sum
if __name__ == "__main__":
func_p = functools.partial(func, a=1, c=1)
sum = func_p(b=1)
print(sum)
Is there something in C++ which offers a similar functionallity?
Upvotes: 3
Views: 2132
Reputation: 76336
Yes, lambda functions:
auto func_p = [](int b){return func(1, b, 1);};
func_p(1);
Incidentally, I personally prefer lambdas in Python too. Consider the following:
lambda b: func(b**2, b, b - 3)
which can't be done with functools
. Why have two different solutions (one applicable only in certain instances)?
There should be one-- and preferably only one --obvious way to do it.
Upvotes: 9
Reputation: 14987
A similar facility in C++ may be std::bind
. See the following code for an illustration:
#include <functional>
#include <iostream>
int func(int a, int b, int c) {
return a + b + c;
}
int main() {
auto func_p = std::bind(func, 1, std::placeholders::_1, 1);
std::cout << func_p(1) << std::endl;
}
Upvotes: 5