Return a functor based on command line input

Viewed 46

From command line input I am receiving a single char of '=','<', or '>' followed by a value and my goal is to iterate through and modify my underlying data container using a custom functor (for example using remove_if). The simple but slow solution would be to have a single functor that is constructed using the input char and switching between the operators within it. However, this requires a check on the operator type every time the functor's operator is called. My first solution was using a switch statement on the char and creating a base functor class with 3 derived classes. However, I realized that while this was a completely viable and fast solution, I ended up having a large amount of code duplication of the switch statements. My attempt at a solution to this was using polymorphism and having a function that accepted the input char and returned a pointer of the base class which had a virtual () operator. However, when I passed the dereferenced base class pointer, it would not accept a pure virtual() operator and it was not overriden by the operators of the derived classes. In a sense, I want a function that returns a particular lambda or comparator assosciated with the value of an input char. What would be a good way of going about this?

1 Answers

Since lambdas have there own type i am not aware of a way to construct a function that returns different lambdas. You could store them in std:: function and pay for the overhead. I think a combination of function ptr and map might be a good solution. Consider using a constexpr map (like in https://youtu.be/INn3xa4pMfg), create your functions and store the mapping in that map. Note that you can also convert a non capturing lambda to a funtion ptr using ClosureType::operator ret(*)(params)() (See https://en.cppreference.com/w/cpp/language/lambda).

Related