1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
|
template< unsigned int i >
struct tupleUnpackCall
{
template< class C, class Tr, class... Args, class... ArgsValue >
static Tr unpack( C *instance, Tr(C::*func)(Args...), std::tuple<Args...> &tuple, ArgsValue... argsVal)
{
tupleUnpackCall< i-1 >::unpack( instance, func, tuple, std::get<i-1>(tuple), argsVal... );
}
};
template<>
struct tupleUnpackCall<0>
{
template< class C, class Tr, class... Args, class... ArgsValue >
static Tr unpack( C *instance, Tr(C::*func)(Args...), std::tuple<Args...> &tuple, ArgsValue... argsVal)
{
(instance->*func)( argsVal... );
}
};
template < class TypeReturn, class... Args>
class EventDispatcher
{
void fireNow( Args... args )
{
// Call for the registered callback functions passing (args...) as argument.
}
void fireLater( int deliveryTime, Args... args )
{
myDelayedList.push_back( std::make_pair(deliveryTime, std::tuple<Args...>{args...}) );
}
void timeUpdate( int currentTime )
{
while( (myDelayedList.size() > 0) && (myDelayedList.front().first <= currentTime ) )
{
for( /*loop the entire callback list*/ )
tupleUnpackCall< sizeof...(Args) >::unpack( iterated_target_instance, &iterated_function_pointer, myDelayedList.front().second );
// is there a better way to unpack the tuple as an argument list of a function ?
myDelayedList.pop_front();
}
}
private:
std::list<std::pair<int, std::tuple<Args...>>> myDelayedList;
}
int main()
{
EventDispatcher< bool, int, std::string > myDispatcher;
/* register for function callbacks with function using bool as return type and int & std::string as arguments */
// Immediate dispatch
myDispatcher.fireNow( 1, "hey 1" ); // fire func( 1, "hey 1")
// Dispatch later
myDispatcher.fireLater( 10000, 2, "hey 2" );
myDispatcher.update( 100 ); // nothing
myDispatcher.update( 15000 ); // fire func( 2, "hey 2")
}
|