Mordachai
Mordachai

Reputation: 9662

What's the boost way to create a functor that binds out an argument

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?

Upvotes: 2

Views: 1557

Answers (1)

tJener
tJener

Reputation: 2619

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.

Upvotes: 4

Related Questions