Opposite of std::bind, pass in different functions for given parameters

You can use a Lambda, which made std::bind mostly obsolete, as it is easier to use:

  auto uber_func = [&](std::function<int(A, B, C, int)> f, int n) {
    return f(a, b, c, n);
  };

  uber_func(hello, 240);
  uber_func(there, 33);
  uber_func(how, 54);
  uber_func(are, 67);

The first solution enforces that all functions have the same well-known interface. If needed it could be generalized to support also different types of functions:

  auto uber_func = [&](auto f, int n) {
    return f(a, b, c, n);
  };

The second solution is more general and avoids the performance overhead of the first solution. Small drawback: it will require a C++14 compiler, while the first should work on any C++11 compiler. If that is no problem, I would prefer the second solution over the first one.

I realized that you asked about how to do it with std::bind and I did not answer that. However, since C++11 Lambdas largely replaced std::bind. Since C++14, it is even clearer, as further improvements have been added. Unless compatibility with C++98 is a strict requirement, I would recommend to avoid std::bind in favor of Lambdas.


You can construct an object with all the parameters but the last:

template<typename A, typename B, typename C>
struct uber
{
   A a;
   B b;
   C c;

   uber(A a, B b, C c) : a(a), b(b), c(c) {}

   template<typename F> 
   auto operator()(F f, int n) { f(a,b,c,n); }
};

and then use the templated call operator to call the individual functions:

A a; B b; C c;
auto uber_func = uber{a,b,c};
uber_func(hello, 240);
uber_func(there, 33);
uber_func(how, 54);
uber_func(are, 67);

Tags:

C++

Std

Stdbind