Can you make custom operators in C++?

前端 未结 6 1933
盖世英雄少女心
盖世英雄少女心 2020-12-01 00:24

Is it possible to make a custom operator so you can do things like this?

if (\"Hello, world!\" contains \"Hello\") ...

Note: this is a sepa

6条回答
  •  半阙折子戏
    2020-12-01 00:33

    There's a method thoroughly explored in 'Syntactic Aspartame' by Sander Stoks that would allow you to use the following format:

    if ("Hello, world!"  "Hello") ...
    

    In essence, you need a proxy object with the operators '<' and '>' overloaded. The proxy does all of the work; 'contains' can just be a singleton with no behavior or data of its own.

    // Not my code!
    const struct contains_ {} contains;
    
    template 
    struct ContainsProxy
    {
        ContainsProxy(const T& t): t_(t) {}
        const T& t_;
    };
    
    template 
    ContainsProxy operator<(const T& lhs, const contains_& rhs)
    {
        return ContainsProxy(lhs);
    }
    
    bool operator>(const ContainsProxy& lhs, const Rect& rhs)
    {
        return lhs.t_.left   <= rhs.left && 
               lhs.t_.top    <= rhs.top && 
           lhs.t_.right  >= rhs.right && 
           lhs.t_.bottom >= rhs.bottom;
    }
    

提交回复
热议问题