tags:

views:

88

answers:

1

I have need for a function pointer that takes two arguments and returns a string.

I would like to pass an adapter that wraps a function that takes one argument, and returns the string (i.e. discard one of the arguments).

I can trivially build my own adapter, that takes the 2 arguments, calls the wrapped function passing just the one argument through.

But I'd much rather have a simple way to create an adapter on the fly, if there is an easy way to do so in C++/boost?

Here's some details to make this a bit more concrete:

typedef boost::function<CString (int,int)> TooltipTextFn;

class MyCtrl
{
public:
    MyCtrl(TooltipTextFn callback = boost::bind(&MyCtrl::GetCellText, this, _1, _2)) : m_callback(callback) { }

    // QUESTION: how to trivially wrapper GetRowText to conform to TooltipTextFn by just discarding _2 ?!
    void UseRowText() { m_callback = boost::bind(&MyCtrl::GetRowText, this, _1, ??); }

private:

    CString GetCellText(int row, int column);
    CString GetRowText(int row);

    TooltipTextFn   m_callback;
}

Obviously, I can supply a member that adapts GetRowText to take two arguments and only passes the first to GetRowText() itself.

But is there already a boost binder / adapter that lets me do that?

+3  A: 

By only providing _1, it will ignore the 2nd parameter given to m_callback and call MyCtrl::GetRowText with one int parameter.

void UseRowText() { m_callback = boost::bind(&MyCtrl::GetRowText, this, _1); }

On the other hand,

void UseRowText() { m_callback = boost::bind(&MyCtrl::GetRowText, this, _2); }

is also valid, where we send the 2nd parameter passed to m_callback into the 1st parameter of MyCtrl::GetRowText.

tJener
VS2008 SP 1 complains on this code. I suspect that boost::bind is creating a functor that takes 1 argument (at least in your first example, which is the one I would need). If there is a way to force the bind to generate a function-signature that matches TooltipTextFn while only using the one argument...
Mordachai
I don't seem to be running into this. I'm working under g++ and don't have readily available access to VS.As an alternate suggestion, is it the `this` pointer in the default parameters of the constructor?
tJener
You're right. The problem I was having was that a ternary conditional wouldn't compile X ? Y : Z. But if I explicitly did an X = Y; then things were fine. Thanks. :)
Mordachai