【问题标题】:Get a function reference with decltype(this)使用 decltype(this) 获取函数引用
【发布时间】:2017-07-03 19:28:21
【问题描述】:

我正在尝试创建一个宏来安装和删除从 lambda 构造的 Qt 事件过滤器。在这种情况下,this 被称为QObject,因此有一个成员destroyedfilter 只是一些QObject 派生的事件过滤器。但是我的线路有问题:

connect(this, &decltype(this)::destroyed, [filter]() 
{ 
    qApp->removeEventFilter(filter); 
    filter->deleteLater();
});

给出 (MSVC2013) 错误:

'::' 的左边必须是类、结构或联合

我只是语法错误,还是不能这样做?

【问题讨论】:

  • this 是一个指针。
  • 在前面加上using 语句(定义decltype(*this) 为别名),并改用别名

标签: c++ qt c++11 visual-studio-2013


【解决方案1】:

根据@molbdnilo 的评论,我没有考虑到this 是一个指针这一事实。使用 type-trait 删除指针使其工作:

connect(this, &std::remove_pointer<decltype(this)>::type::destroyed, [filter]() 
{
    qApp->removeEventFilter(filter);
    filter->deleteLater();
});

【讨论】:

  • 值得注意的是,c++14 引入了std::remove_pointer_t&lt;T&gt;,它取代了typename std::remove_pointer&lt;T&gt;::type
  • @FrançoisAndrieux 感谢您指出这一点,但我被 msvc2013/c++11 困在这个特定的任务中!
  • @NicolasHolthaus:为什么不直接使用&amp;decltype(*this)::destroyed?甚至只是&amp;destroyed,因为您显然已经在定义destroyed()的类中
  • @RemyLebeau 前者对引用类型使用::无效;后者不构成指向成员的指针。
  • @RemyLebeau 不,它们不是同一类型。你为什么不试试呢?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-25
  • 2014-10-08
  • 1970-01-01
  • 2019-08-20
  • 1970-01-01
  • 2014-09-03
相关资源
最近更新 更多