1

I am trying to create an array of pointers to MainWindow functions, because I need to loop and execute all of the functions associated with my pushbuttons and spinboxes automatically. Here is the sample code:

typedef void (*f_pointer)();

void MainWindow::on_test_spinBox_valueChanged(int a){
ui->label->setNum(a);
}

void MainWindow::on_test_pushButton_clicked() {
int a = 1 + 2;
}

void MainWindow::on_test2_pushButton_clicked() {
int a = 2 + 3;
}

void MainWindow::on_run_all_pushButton_clicked() {
f_pointer array[]  = { MainWindow::on_test_spinBox_valueChanged(), MainWindow::on_test2_pushButton_clicked(), MainWindow::on_test_pushButton_clicked() };

for (int i = 0; i < 2; i++)
array[i];
}

All of this results in error: void value not ignored as it ought to be.

Can you help? Thanks.

parameter2
  • 13
  • 2

2 Answers2

1

The main error (that reported) is that, in your initializer list, you have calls to the three functions, rather than their addresses. You should remove the parentheses after the functions names to specify those functions' addresses rather than their returned values. But note: this can only be done for static class member functions; for non-static member functions, the syntax is trickier: Calling C++ class methods via a function pointer.

Also, your first function in the list does not have the correct signature for its address to be an f_pointer, as it has an int a argument.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • In my example all of the functions that I want to put in the array should have some int as an argument. Updating typedef void (MainWindow::*f_pointer)(int); and array initializer list with & seem to have resolved the original error. Is there a way for me to pass an int to each of the array items when I loop through it and execute? – parameter2 Jun 05 '20 at 14:57
  • @parameter2 Yes: if the `int` argument you want to pass is called (say) `x`, then you just need to add that as an argument after the array specifier: `array[i](x);` will call the function pointed to by the `i` element, with `x` as its argument. – Adrian Mole Jun 05 '20 at 15:11
0

When building your list, this code:

MainWindow::on_test_spinBox_valueChanged()

Gives you the return value of that function. It will actually call it. What happens when you put a void in an array, I don't know. What you want is:

&MainWindow::on_test_spinBox_valueChanged

However, why do you do the loop? You already have a function that lists all the functions. Just call them instead. The array and loop just adds code to your project. Eg.

void MainWindow::on_run_all_pushButton_clicked() {
    MainWindow::on_...();
    ...
    MainWindow::on_...();
}

But, there is an even better way. You can daisy-chain signals. So make the on_run_all_pushButton_clicked a signal, then connect it to the on_test_spinBox_valueChanged and so on. See: http://thesmithfam.org/blog/2005/09/16/qt-connecting-signals-to-signals/ .

e8johan
  • 2,899
  • 17
  • 20