0

I would like to do the following. Say I have this:

void f(const char* c) {
    // Do stuff with c
}

void g(const char* c, int x, int y) {
    // Do other stuff
}

What I'd like to do is to create a function from g that takes a const char* c. That is:

int a = 5;
int b = 9;
expression(g, a, b)("Hi!");

Preferably, expression(g) can be stored in a variable as well. I'm not sure how to declare this variable either.

I have tried using boost::bind; however boost::bind returns a boost::function, and I would like a normal C++ function pointer. Additionally, I also saw this thread: demote boost::function to a plain function pointer And neither of the top two solution will work. My function f is constrained to take one parameter (no void* user_data pointer). The reason I need this is that I have a third function, h, that takes in a function of one argument, namely a const char* and does things with it. I'd like to be able to pass in a form of g to h.

h(f) // Valid
h(expression(g, a, b)) // Would like for this to be valid, too

I'm not sure if this is possible, but if it is, do tell :).

Community
  • 1
  • 1
Toan
  • 1
  • 1

1 Answers1

2

Use bind:

#include <functional>

auto h = std::bind(g, std::placeholders::_1, 5, 9);

h("hi");

bind makes copies of the arguments, so beware if you're planning on taking arguments by reference (in which case you may want std::ref). Try to keep the result type auto to avoid unnecessary conversions.


To get a normal C++ function:

void h(char const * s) { g(s, 5, 9); }

Or:

void (*ph)(char const *) = [](const char * s) { g(s, 5, 9); };

Or for the insane:

struct Foo { static void bar(char const * s) { g(s, 5, 9); } };
void (*qh)(char const *) = &Foo::bar;

Usage:

h("hi");
ph("hi");
Foo::bar("hi");
qh("hi");
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • I've already tried bind, but like I said bind::boost returns a boost::function. What I'd like is a normal c++ function. – Toan Feb 14 '13 at 01:48
  • Thanks for your quick reply. I should have been more clear. I'd like the arguments to g (The 5 and 9 in your example) to be parameters as well. That is, void t(int a, int b) { return expression(g, a, b); // Returns a function that takes a const char* } t(3, 5)("Hello"); // g("Hello", 3, 5); – Toan Feb 14 '13 at 02:01
  • You can't have plain function pointer with expression you wish. first expression would first have to store 3 and 5 parameters, and with second () statement it would have to execute g. So it's either lambda, binded function, or custom struct. TBH I don't see reason for what you want to accompish. – rAndom69 Feb 03 '14 at 05:53