Extension methods in c++

后端 未结 6 1541
我在风中等你
我在风中等你 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:32

    Boost Range Library's approach use operator|().

    r | filtered(p);
    

    I can write trim for string as follows in the same way, too.

    #include 
    
    namespace string_extension {
    
    struct trim_t {
        std::string operator()(const std::string& s) const
        {
            ...
            return s;
        }
    };
    
    const trim_t trim = {};
    
    std::string operator|(const std::string& s, trim_t f)
    {
        return f(s);
    }
    
    } // namespace string_extension
    
    int main()
    {
        const std::string s = "  abc  ";
    
        const std::string result = s | string_extension::trim;
    }
    

提交回复
热议问题