You know, we can wrap or store a lambda function to a std::function
:
#include
#include
int main()
{
std:
It uses some type erasure technique.
One possibility is to use mix subtype polymorphism with templates. Here's a simplified version, just to give a feel for the overall structure:
template
struct function;
template
struct function {
private:
// this is the bit that will erase the actual type
struct concept {
virtual Result operator()(Args...) const = 0;
};
// this template provides us derived classes from `concept`
// that can store and invoke op() for any type
template
struct model : concept {
template
model(U&& u) : t(std::forward(u)) {}
Result operator()(Args... a) const override {
t(std::forward(a)...);
}
T t;
};
// this is the actual storage
// note how the `model>` type is not used here
std::unique_ptr fn;
public:
// construct a `model`, but store it as a pointer to `concept`
// this is where the erasure "happens"
template ()...) ),
Result
>::value
>::type>
function(T&& t)
: fn(new model::type>(std::forward(t))) {}
// do the virtual call
Result operator()(Args... args) const {
return (*fn)(std::forward(args)...);
}
};
(Note that I overlooked several things for the sake of simplicity: it cannot be copied, and maybe other problems; don't use this code in real code)