Giter VIP home page Giter VIP logo

Comments (1)

marty1885 avatar marty1885 commented on September 27, 2024

Quick update, this modified code is slightly faster than the above code. 1. Returns a reference to std::function and reads a reference of std::function from std::any. 2. Use a std::string_view as key instead of std::string. But this feature requires C++20

 struct BackendBase
 {
         std::map<std::string, std::any> funcs_;
 
         template<typename Class, typename Return, typename ...Args>
         void expose_method(const std::string& name, Return(Class::*func)(Args...))
         {   
                 funcs_[name] = std::function<Return(Args...)>([this, func](Args ... args) { 
                         (static_cast<Class*>(this)->*func)(args...);
                 }); 
         }   
 
         template <typename Func>
         const std::function<Func>& get_method(const std::string_view name)
         {   
                 return std::any_cast<const std::function<Func>&>(funcs_.at(name));
         }   
 };

This is not the final design tho. I still want to remove the use of std::function and use a custom, more specific class. Hopefully the method wrapper can ensure no allocation what so ever.


Update: The current lambda needs exactly 24 bytes of storage space on 64bit systems. Which is exactly how much space libc++'s std::function have for small functions. No heap allocations. We are good in that regards :)

from etaler.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.