Extending template call back code to any number of Args using variadic
templates
Hi I have the following templated call back code that I created tonight
but it is currently for a single argument. Ideally I would like to put
Args... for all the parameters but being somewhat new to variadic
templates I was wondering if there was an easy way like just adding
Args... everywhere. I tried this and it didn't compile so I thought I
would ask for some pointers first before proceeding. Thanks in advance.
#include <iostream>
#include <vector>
template <typename R, typename Arg>
class Callback
{
public:
typedef R (*FuncType)(void*, Arg);
Callback (FuncType f, void* subscription) : f_(f),
subscription_(subscription) { }
R operator()(Arg a)
{
(*f_)(subscription_,a);
}
private:
FuncType f_;
void* subscription_;
};
template <typename R, typename Arg, typename T, R (T::*Func)(Arg)>
R CallbackWrapper (void* o, Arg a)
{
return (static_cast<T*>(o)->*Func)(a);
}
class Pricer
{
public:
typedef Callback<void,unsigned int> CbType;
void attach ( CbType cb )
{
callbacks_.emplace_back(cb);
}
void receivePrice ( double price )
{
broadcast(static_cast<unsigned int>(price*100));
}
void broadcast (unsigned int price)
{
for ( auto& i : callbacks_)
{
i(price);
}
}
private:
std::vector<CbType> callbacks_;
};
class Strategy
{
public:
Strategy(Pricer* p) : p_(p)
{
p->attach(Callback<void,unsigned int>(&CallbackWrapper<void,unsigned
int, Strategy, &Strategy::update>, static_cast<void *>(this)));
}
void update(unsigned int price)
{
//update model with price
std::cout << "Received price: " << price / 100.0 << std::endl;
}
private:
Pricer* p_;
};
int main ( int argc, char *argv[])
{
Pricer p;
Strategy s(&p);
p.receivePrice(105.67);
}
No comments:
Post a Comment