Mattia F.
Mattia F.

Reputation: 1740

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 some labels.

template <class R, class ...Args>
void ClockSim::applyToLabels (R (QLabel::*f)(Args...), Args&& ...args)
{
    ui->labelSingleTime->*f (std::forward<Args>(args)...);
    //Repeat it for many other labels

}

I tried to call it with:

applyToLabels (&QLabel::setStyleSheet, "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

Upvotes: 1

Views: 124

Answers (1)

aschepler
aschepler

Reputation: 72271

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.

Upvotes: 5

Related Questions