I have a data type OperationSequence
. Below is OperationSequence.h
class OperationSequence
{
public:
void appendOperation(std::function<double(double)> operation);
void moveOperation(int operation_index);
void eraseOperation(int operation_index);
const std::vector<std::function<double(double)>>& data() const;
private:
std::vector<std::function<double(double)>> operation_sequence;
};
double executeSequence(const OperationSequence& operation_sequence, double value);
void executeSequence(const OperationSequence& operation_sequence, const std::string& file_name);
I have to implement printOperationSequence(const OperationSequence& operation_sequence).
Assignment set a requirement on operation to be f: double -> double
. Some operations like Addition
and Multiplication
were also requested. Obvious implementation would be to create an Interface Operation
and have it be callable with f: double -> double
and have a std::string getName()
method.
What would be a good way for OperationSequence to remain this generic but also making it easy and efficient to print out OperationSequence in a meaningful way?
Meaningful way being something like Multiplication, Addition, ...
Is delegating construction to some other class that will also create a operation_name_sequence a good idea?
PS Feel free to improve the question title :D
If you want to avoid to have polymorphism (even if std::function
uses it or similar for type erasure), you might create class Operation
to add name to the function:
struct Operation
{
std::string name;
std::function<double(double)> f;
};
class OperationSequence
{
public:
void appendOperation(const Operation& operation);
void appendOperation(const std::string& name, std::function<double(double)> f);
void moveOperation(int operation_index);
void eraseOperation(int operation_index);
const std::vector<Operation>& data() const;
private:
std::vector<Operation> operations;
};
then
void printOperationSequence(const OperationSequence& operation_sequence)
{
for (const auto& op : operation_sequence.data()) {
std::cout << op.name << std::endl;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.