QVariant的访客模式(无需手动类型测试和投射)

时间:2016-06-28 08:52:10

标签: c++ qt visitor visitor-pattern qvariant

Qt的QVariant类是否有任何现有(且方便)的访问者模式实现?

如果没有,是否有可能实现与boost::apply_visitor()类似的东西,即最小化测试类型和铸造方面的重复?

我希望通过以下方式实现目标:

/* I have a QVariant that can contain anything, including user types */
QVariant variant;    

/* But in my Visitor I'm interested only in ints and QStrings (for the sake of the example) */
struct Visitor
{
   void operator()(int i) { /* do something with int */ } 
   void operator()(QString s) { /* ...or QString */ }
};

/* The question is: */
/* Can this be implemented in a generic way (without resorting to particular template parameters)? */
template <typename VisitorT>
void visit(QVariant variant, VisitorT visitor)
{
   if (variant.canConvert<int>()) {
      visitor(variant.value<int>());
   } else if (variant.canConvert<QString>()) {
      visitor(variant.value<QString>());
   } /* and so on (if needed for other types)... */
}

/* So that later I can use it like that */
visit(variant, Visitor());

编辑1:QVariant::canConvert<T>()可能不是上述最佳解决方案,但关键是:类型映射(QMetaTypetypename T之间)是否可以自动实现?

编辑2:&#34;访客编程器&#34;或者&#34;访客功能&#34;对我来说并不重要。重要的是我想避免测试类型和铸造(如果可能的话)。

1 个答案:

答案 0 :(得分:6)

内省访客

您可以利用moc生成的内省信息。声明您的访问者为Q_GADGET。这会向访问者添加一个静态staticMetaObject成员,其中包含有关可调用方法的信息。

// https://github.com/KubaO/stackoverflown/tree/master/questions/variant-convert-38071414
#include <QtCore>

struct Foo {
   int a;
   Foo() = default;
   explicit Foo(int a) : a(a) {}
};
QDebug operator<<(QDebug debug, const Foo & f) {
   return debug << f.a;
}
Q_DECLARE_METATYPE(Foo)

struct Visitor
{
   Q_GADGET
   Q_INVOKABLE void visit(int i) { qDebug() << "got int" << i; }
   Q_INVOKABLE void visit(const QString & s) { qDebug() << "got string" << s; }
   Q_INVOKABLE void visit(const Foo & f) { qDebug() << "got foo" << f; }
};

Qt具有将opaque类型作为可调用方法的参数传递所需的所有信息:

template <typename V>
bool visit(const QVariant & variant, const V & visitor) {
   auto & metaObject = V::staticMetaObject;
   for (int i = 0; i < metaObject.methodCount(); ++i) {
      auto method = metaObject.method(i);
      if (method.parameterCount() != 1)
         continue;
      auto arg0Type = method.parameterType(0);
      if (variant.type() != (QVariant::Type)arg0Type)
         continue;
      QGenericArgument arg0{variant.typeName(), variant.constData()};
      if (method.invokeOnGadget((void*)&visitor, arg0))
         return true;
   }
   return false;
}

也许这就是你所追求的:

int main() {
   visit(QVariant{1}, Visitor{});
   visit(QVariant{QStringLiteral("foo")}, Visitor{});
   visit(QVariant::fromValue(Foo{10}), Visitor{});
}

#include "main.moc"

示例结束。

非内省访客

您可以将转换分解为类型和条件代码执行:

void visitor(const QVariant & val) {
   withConversion(val, [](int v){
      qDebug() << "got an int" << v;
   })
   || withConversion(val, [](const QString & s){
      qDebug() << "got a string" << s;
   });
}

int main() {
   visitor(QVariant{1});
   visitor(QVariant{QStringLiteral("foo")});
}

withConversion函数推导出callable的参数类型,如果变量属于匹配类型,则调用callable:

#include <QtCore>
#include <type_traits>

template <typename T>
struct func_traits : public func_traits<decltype(&T::operator())> {};

template <typename C, typename Ret, typename... Args>
struct func_traits<Ret(C::*)(Args...) const> {
   using result_type = Ret;
   template <std::size_t i>
   struct arg {
      using type = typename std::tuple_element<i, std::tuple<Args...>>::type;
   };
};

template <typename F> bool withConversion(const QVariant & val, F && fun) {
   using traits = func_traits<typename std::decay<F>::type>;
   using arg0_t = typename std::decay<typename traits::template arg<0>::type>::type;
   if (val.type() == (QVariant::Type)qMetaTypeId<arg0_t>()) {
      fun(val.value<arg0_t>());
      return true;
   }
   return false;
}

有关callables中参数类型推导的更多信息,请参阅this question