Search code examples
c++wt

Passing A Parameter Along with a Function Pointer


I am using the Wt C++ library in a project. I am trying to use the connect(...) function to connect a slot to a button press. The documentation for the connect(...) function can be found here.

Essentially, each time a change is detected in a group of radio buttons, the function passed as a pointer to the connect(...) function is called.

Below is a short snippet of the code:

...

_group = new Wt::WButtonGroup(this);
Wt::WRadioButton *button;

button = new Wt::WRadioButton("Radio Button 0", this);
_group->addButton(button, 0);

_group->setSelectedButtonIndex(0); // Select the first button by default.

_group->checkedChanged().connect(this, (&MyWidget::RadioButtonToggle)); //Need to pass parameter here  

...

I need to pass the selection parameter to the functionRadioButtonToggle(Wt::WRadioButton *selection) so that I can use it in the function body as seen below:

void CycleTimesWidget::RadioButtonToggle(Wt::WRadioButton *selection)
{
    switch (_group->id(selection))
    {
        case 0:
    {
            //Do something...
            break;
        }
    }
}

How can I pass a parameter along with this function pointer?


Solution

  • You could use an Wt:WSignalMapper, documentation can be found here. With a Wt:WSignalMapper you can connect multiple senders to a single slot. The multiple senders are in your case the different Wt:WRadioButton.

    Wt::WSignalMapper<Wt:WRadioButton *> * mapper = new Wt::WSignalMapper<
            Wt::WRadioButton *>(this);
    mapper->mapped().connect(this, &MyWidget::RadioButtonToggle);
    
    // for all radio buttons
    mapper->mapConnect(button->changed(), button);
    ...
    

    You can then use your function RadioButtonToggle as written above in your question.

    Update:

    As pointed out in the comments, a Wt:WSignalMapper is outdated. You should now use boost::bind() or std::bind() if you use C++ 11 or higher. The code then becomes:

    // for all radio buttons
    button->changed().connect(boost::bind(this, &MyWidget::RadioButtonToggle, button));