Ref T125, allow to use std::function with CSlot

This commit is contained in:
Klaus Basan
2017-08-16 12:09:41 +02:00
committed by Mathew Sutcliffe
parent d4b027b6bd
commit 8d72fe5285
2 changed files with 18 additions and 2 deletions

View File

@@ -78,6 +78,13 @@ namespace BlackMisc
CSlot(T *object, R(U::* function)(Args...)) : CSlot(T *object, R(U::* function)(Args...)) :
m_object(object), m_object(object),
m_function([ = ](Args... args) { return (object->*function)(args...); }) m_function([ = ](Args... args) { return (object->*function)(args...); })
{
Q_ASSERT_X(object, Q_FUNC_INFO, "Need object");
}
//! Construct a slot from the given object passing a function
CSlot(std::function<R(Args...)> function) :
m_function(function)
{} {}
//! Call the slot. The behaviour is undefined if the slot is empty. //! Call the slot. The behaviour is undefined if the slot is empty.
@@ -94,6 +101,14 @@ namespace BlackMisc
return m_object.data(); return m_object.data();
} }
//! Set the object which the slot belongs to.
//! Use this as the third argument to QObject::connect to ensure the slot is called in the correct thread.
void setObject(QObject *object)
{
Q_ASSERT_X(hasNullObject(), Q_FUNC_INFO, "Can only set, not change the object");
m_object = object;
}
//! True if the slot can be called, false if it is empty. //! True if the slot can be called, false if it is empty.
operator bool() const operator bool() const
{ {

View File

@@ -30,8 +30,9 @@ namespace BlackMiscTest
CSlot<void(const QString &)> slot1 = { obj, &QObject::setObjectName }; CSlot<void(const QString &)> slot1 = { obj, &QObject::setObjectName };
QVERIFY2(slot1, "Slot has valid object and function - can be called."); QVERIFY2(slot1, "Slot has valid object and function - can be called.");
CSlot<void(const QString &)> slot2 = { static_cast<QObject*>(nullptr), &QObject::setObjectName }; // KB 8/17 T125, CSlot can no longer be constructed with null object
QVERIFY2(!slot2, "Slot has an invalid pointer - cannot be called."); // CSlot<void(const QString &)> slot2 = { static_cast<QObject*>(nullptr), &QObject::setObjectName };
// QVERIFY2(!slot2, "Slot has an invalid pointer - cannot be called.");
CSlot<void(const QString &)> slot3; CSlot<void(const QString &)> slot3;
QVERIFY2(!slot3, "Slot has an invalid pointer and invalid function - cannot be called."); QVERIFY2(!slot3, "Slot has an invalid pointer and invalid function - cannot be called.");