E-MailRelay
Classes | Functions
G::Slot Namespace Reference

A callback mechanism that isolates event sinks from event sources. More...

Classes

struct  Binder
 A functor class template that contains the target object pointer and method pointer, similar to c++20 bind_front(&T::fn,tp). More...
 
struct  Signal
 A slot holder, with connect() and emit() methods. More...
 
struct  SignalImp
 A slot/signal scoping class.
 
struct  Slot
 A slot class template that is parameterised only on the target method's signature (with an implicit void return) and not on the target class. More...
 

Functions

template<typename TSink , typename... Args>
Slot< Args... > slot (TSink &sink, void(TSink::*method)(Args...))
 A factory function for Slot objects. More...
 

Detailed Description

A callback mechanism that isolates event sinks from event sources.

The slot/signal pattern has been used in several C++ libraries including libsigc++, Qt and boost, although it is largely redudant with modern C++. The pattern is completely unrelated to ANSI-C or POSIX signals (signal(), sigaction(2)).

Usage:

struct Source
{
void Source::raiseEvent()
{
m_signal.emit( 123 ) ;
}
} ;
struct Sink
{
void onEvent( int n ) ;
Sink( Source & source ) : m_source(source)
{
source.m_signal.connect( G::Slot::slot(*this,&Sink::onEvent) ) ;
}
~Sink()
{
m_source.m_signal.disconnect() ;
}
Sink( const Sink & ) = delete ;
Sink( Sink && ) noexcept { rebind() ; }
Sink & operator=( const Sink & ) = delete ;
Sink & operator=( Sink && ) noexcept { rebind() ; return *this ; }
void rebind() noexcept( check( m_source.m_signal.rebind(*this) ) ; }
Source & m_source ;
} ;
Slot< Args... > slot(TSink &sink, void(TSink::*method)(Args...))
A factory function for Slot objects.
Definition: gslot.h:240

For comparison the equivalent modern C++ looks like this:

struct Source
{
std::function<void(int)> m_signal ;
void Source::raiseEvent()
{
if( m_signal ) m_signal( 123 ) ;
}
} ;
struct Sink
{
void onEvent( int n ) ;
Sink( Source & source ) : m_source(source)
{
throw_already_connected_if( !source.m_signal ) ;
source.m_signal = std::bind_front(&Sink::onEvent,this) ;
}
~Sink()
{
m_source.m_signal = nullptr ;
}
Source & m_source ;
} ;

Slot methods should take parameters by value or const reference but beware of emit()ing references to data members of objects that might get deleted. Use temporaries in the emit() call if in doubt.

Function Documentation

◆ slot()

template<typename TSink , typename... Args>
Slot< Args... > G::Slot::slot ( TSink &  sink,
void(TSink::*)(Args...)  method 
)

A factory function for Slot objects.

Definition at line 240 of file gslot.h.