Can I create a new operator in C++ and how?

前端 未结 9 958
耶瑟儿~
耶瑟儿~ 2020-11-27 18:43

MATLAB arrays support matrix operations and element operations. For example, M*N and M.*N. This is a quite intuitive way to distinguish ‎the two di

9条回答
  •  暖寄归人
    2020-11-27 19:07

    In C++, there's a list of predefined operators, most of which are overloadable (.* is not). Additionally, any name can be used as an operator like:

    #include 
    
    // generic LHSlt holder
    template
    struct LHSlt {
        LHS lhs_;
    };
    
    // declare myop as an operator-like construct
    enum { myop };
    
    // parse 'lhs 
    LHSlt operator<(const LHS& lhs, decltype(myop))
    {
        return { lhs };
    }
    
    // declare (int  int) -> int
    int operator>(LHSlt lhsof, int rhs)
    {
        int& lhs = lhsof.lhs_;
        // here comes your actual implementation
        return (lhs + rhs) * (lhs - rhs);
    }
    
    // strictly optional
    #define MYOP 
    
    int main() {
        std::cout << (5  2) << ' ' << (5 MYOP 2);
    }
    

    Disclaimer: This, strictly speaking, gets translated to (5 < myop) > 2, which is LHSlt(5) > 2. Thus it's not a new 'operator', in C++-terms, but it's used exactly the same way, even in terms of ADL. Also, if type is large, you probably want to store const T&.

    Note that you can do this with any binary operator that can be defined external to the class; precedence is based on the precedence of the two sides (< and >). Thus you can have e.g. *myop*, +myop+, <>, , |myop| in this order of precedence.

    If you want right-associativity, it gets a bit more tricky. You'll need both of a RHS-holder and LHS-holder (the latter being LHSlt here) and use surrounding operators such that the right one has higher precedence than the left one, e.g. a |myop> b |myop>c is a |myop> (b |myop> c). Then you need the function for both your type and your holder type as the lhs.

提交回复
热议问题