lundi 29 février 2016

Variadic Template for qobject_cast via parent()

gurus and template-experts, I need your help ...

I am currently looking for a solution on checking a QObject's parent hierarchy. I have a custom QDialog with the following hierarchy (parent to child):

QDockWidget
> CustomDockArea
  > QMainWindow
    > QDockWidget
      > CustomDialog

Within the CustomDialog class, I want to check if the hierarchy is correct, so I checked if this is accomplishable with a variadic template, for example:

assert(qobject_cast_parent<QDockWidget*, QMainWindow*, CustomDockArea*, QDockWidget*>(this));

and I have come up with something like this:

template <class T, class... Ts>
inline T qobject_cast_parent(QObject* root)
{
    if (root)
    {
        if (sizeof...(Ts) == 0)
        {
            return qobject_cast<T>(root->parent());
        }
        else
        {
            return qobject_cast_parent<Ts...>(root->parent());
        }
    }
    else
    {
        return nullptr;
    }
}

However, there a few problems: I need the last parameter of the parameter pack as being the return type of the function, in our example QDockWidget*. I could take the first parameter as being the return type, but this would make the template call a little bit cumbersome. However, even if that would be solved, I think there is still a problem with the way the parameter pack is "unrolled" and now I got a little bit unsure if my template-approach is even feasible for the original problem. Maybe you can give me some hints. Thanks in advance!!!

Aucun commentaire:

Enregistrer un commentaire