Extension methods in c++

后端 未结 6 1558
我在风中等你
我在风中等你 2020-11-27 16:38

I was searching for an implementation of extension methods in c++ and came upon this comp.std.c++ discussion which mentions that polymorphic_map can be used to

6条回答
  •  我在风中等你
    2020-11-27 17:27

    You can enable kinda extension methods for your own class/struct or for some specific type in some scope. See rough solution below.

    class Extensible
    {
    public:
        template
        std::function operator|
            (std::function& extension)
        {
            return [this, &extension](Args... args) -> TRes
            {
                return extension(*static_cast(this), std::forward(args)...);
            };
        }
    };
    

    Then inherit your class from this and use like

    class SomeExtensible : public Extensible { /*...*/ };
    std::function fn;
    SomeExtensible se;
    int i = (se | fn)(4);
    

    Or you can declare this operator in cpp file or namespace.

    //for std::string, for example
    template
    std::function operator|
        (std::string& s, std::function& extension)
    {
        return [&s, &extension](Args... args) -> TRes
        {
            return extension(s, std::forward(args)...);
        };
    }
    
    std::string s = "newStr";
    std::function init = [](std::string& s) {
        return s = "initialized";
    };
    (s | init)();
    

    Or even wrap it in macro (I know, it's generally bad idea, nevertheless you can):

    #define ENABLE_EXTENSIONS_FOR(x) \
    template \
    std::function operator| (x s, std::function& extension) \
    { \
        return [&s, &extension](Args... args) -> TRes \
        { \
            return extension(s, std::forward(args)...); \
        }; \
    }
    
    ENABLE_EXTENSIONS_FOR(std::vector&);
    

提交回复
热议问题