c++ - How std::function works -
you know, can wrap or store lambda function std::function:
#include <iostream> #include <functional> int main() { std::function<float (float, float)> add together = [](float a, float b) // ^^^^^^^^^^^^^^^^^^^^ { homecoming + b; }; std::cout << add(1, 2) << std::endl; } my question around std::function, can see template class can take kind of function signature.
for illustration float (float, float) in form return_value (first_arg, second_arg).
what's construction of std::function , how take function signature x(y,z) , how works it? float (float, float) new valid look in c++?
it uses type erasure technique.
one possibility utilize mix subtype polymorphism templates. here's simplified version, give sense overall structure:
template <typename t> struct function; template <typename result, typename... args> struct function<result(args...)> { private: // bit erase actual type struct concept { virtual result operator()(args...) const = 0; }; // template provides derived classes `concept` // can store , invoke op() type template <typename t> struct model : concept { template <typename u> model(u&& u) : t(std::forward<u>(u)) {} result operator()(args... a) const override { t(std::forward<args>(a)...); } t t; }; // actual storage // note how `model<?>` type not used here std::unique_ptr<concept> fn; public: // build `model<t>`, store pointer `concept` // erasure "happens" template <typename t, typename=typename std::enable_if< std::is_convertible< decltype( t(std::declval<args>()...) ), result >::value >::type> function(t&& t) : fn(new model<typename std::decay<t>::type>(std::forward<t>(t))) {} // virtual phone call result operator()(args... args) const { homecoming (*fn)(std::forward<args>(args)...); } }; (note overlooked several things sake of simplicity: cannot copied, , maybe other problems; don't utilize code in real code)
c++ c++11
No comments:
Post a Comment