I have 3 different classes, the class - consumer is being used by the user. I basically wanted the user to give the method that has to be executed in case of error in worker. So I have to pass this to worker class somehow
The consumer class instantiates a subscriber class and that in turn instantiates a worker class. I have a method in consumer class - onerrorReceived. I want to pass this function as a parameter to subscribe.create method which would call the constructor of subscribe and that would pass the function to the worker's constructor. The worker method will internally call this method in case of any error.
I read about lambda, std::func, std::bind and I tried to implement this but I am unable to.
consumer class:
auto consumer = std::make_shared<RdConsumer>(topics.size());
auto Subscriber = Subscriber::create(conf, consumer, [&consumer](){ consumer->onerrorReceived(); });
In the subcriber.h,
Subscriber(const Configuration& conf, IRecordConsumerPtr consumer, std::function<void(std::exception_ptr)>);
static std::shared_ptr<Subscriber> create(const Configuration& conf, IRecordConsumerPtr consumer, std::function<void(std::exception_ptr)> f);
In subscriber.C
std::shared_ptr<Subscriber> Subscriber::create(const Configuration& conf,
IRecordConsumerPtr consumer,
std::function<void(std::exception_ptr)> f)
{
auto subscriberPtr = std::shared_ptr<Subscriber>(new Subscriber(conf, consumer, std::bind(&f)));
return subscriberPtr;
}
Subscriber::Subscriber(const Configuration& conf, IRecordConsumerPtr consumer, std::function<void(std::exception_ptr)> f)
: myLogger(cpplogger::get_instance("class.cp.Subscriber")), myConsumer(consumer),
myWorker(std::make_shared<Worker>("Common Worker"), std::bind(&f))
{}
In Worker.h
explicit Worker(std::string name, std::function<void(std::exception_ptr)> f);
std::function<void(std::exception_ptr)> callback;
Worker.C
Worker::Worker(std::string name, std::function<void(std::exception_ptr)> f) : myName(std::move(name)), callback(f)
{}
...
void Worker::run()
{
try {
...
} catch (const std::exception& e) {
std::exception_ptr eptr = std::current_exception();
callback(eptr);
}
}
Can someone point out what I am missing here. I am new to c++. So please point me some valuable resource where I can learn to get this thing fixed.