2

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?

user69453
  • 1,279
  • 1
  • 17
  • 43
  • 1
    You're looking for lambdas or `std::bind`. (the latter is probably the most direct counterpart of `partial`) – Columbo May 16 '15 at 10:12

2 Answers2

8

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.

Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
  • 1
    I gave your answer an upvote since it works; although have a look at this answer and you might rethink your general opinion on functools http://stackoverflow.com/a/3252425/4408275 – user69453 May 16 '15 at 14:18
  • @user69453 It **was** very interesting. However, on second thought, all his points seem relevant to Python, not C++. So if in Python it's a tradeoff, I still don't see much of a use for ``bind`` in C++. – Ami Tavory May 16 '15 at 14:25
  • yes the provided link was meant only for python. I just liked the syntax of `bind` more in c++. Thats all ;) – user69453 May 16 '15 at 14:28
4

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;
}
Lingxi
  • 14,579
  • 2
  • 37
  • 93