I want to have a class which starts different calculations asynchronously, but also conforms to an inherited structure, so an initialization process need only to be defined once.
After a deeper search I found this question, which in the end helped me to produce the working example code below:
main.h:
#include <functional>
#include <future>
class Switchable{
protected:
int call_calculations(std::function< int(int) > fun, int input){
/* Some lengthy initialization of the calculations */
std::future<int> retval= std::async(fun, input);
return retval.get();
}
};
main.cpp:
#include "main.h"
#include <iostream>
using namespace std;
using std::placeholders::_1;
class My_switchable : public Switchable{
public:
int callCalculation(bool call_first, int number){
if(call_first){
return call_calculations(std::bind(&My_switchable::calculation1, this, _1), number);
}else{
return call_calculations(std::bind(&My_switchable::calculation1, this, _1), number);
}
}
private:
int calculation1(int in){
return in * 5;
}
int calculation2(int in){
return in + 2;
}
};
int main(){
My_switchable some_calculation;
cout << some_calculation.callCalculation(true, 30) << endl;
return 0;
}
This works as intended, however seems a bit too complicated, and has the suspicion of an Anti-pattern. Are there simpler alternatives to be applied here that would be easily maintainable? How could this design be improved?
Thank you for any suggestions in advnace!
Aucun commentaire:
Enregistrer un commentaire