Mattia F. Mattia F. - 4 months ago 9
C++ Question

Pass function member pointer as parameter to function

I'm working on a Qt project and I have decided to implement a function which takes a pointer to a

QLabel
member function and its parameters, and applies it to a label.

template <class R, class ...Args>
void ClockSim::applyToLabels (R (QLabel::*f)(Args...), Args&& ...args)
{
ui->labelSingleTime->*f (std::forward<Args>(args)...);
}


I tried to call it with:

applyToLabels (&QLabel::setStylesSheet, "color:red;");


It says:

error: no matching member function for call to 'applyToLabels'

candidate template ignored: could not match 'QLabel' against 'QWidget'

Any solution? Thanks

Answer

Since setStylesSheet is an inherited member of QWidget, the type of &QLabel::setStylesSheet is actually void (QWidget::*)(const QString&), and that doesn't match your template function parameter.

You'll need to use another template parameter for the actual class of the member function:

template <class R, class C, class ...Params, class ...Args>
typename std::enable_if<std::is_base_of<C,QLabel>::value &&
                        sizeof...(Params)==sizeof...(Args)>::type 
ClockSim::applyToLabels (R (C::*f)(Params...), Args&& ...args)
{
    (ui->labelSingleTime->*f)(std::forward<Args>(args)...);
}

I've also made the function pointer parameters different from your passed args, since you try to pass a const char(&)[11] which is not a QString but converts to one.