Can you make custom operators in C++?

前端 未结 6 1934
盖世英雄少女心
盖世英雄少女心 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条回答
  •  旧时难觅i
    2020-12-01 00:32

    I've created the following two macros:

    #define define const struct
    #define operator(ReturnType, OperatorName, FirstOperandType, SecondOperandType) OperatorName ## _ {} OperatorName; template  struct OperatorName ## Proxy{public:OperatorName ## Proxy(const T& t) : t_(t){}const T& t_;static ReturnType _ ## OperatorName ## _(const FirstOperandType a, const SecondOperandType b);};template  OperatorName ## Proxy operator<(const T& lhs, const OperatorName ## _& rhs){return OperatorName ## Proxy(lhs);}ReturnType operator>(const OperatorName ## Proxy& lhs, const SecondOperandType& rhs){return OperatorName ## Proxy::_ ## OperatorName ## _(lhs.t_, rhs);}template  inline ReturnType OperatorName ## Proxy::_ ## OperatorName ## _(const FirstOperandType a, const SecondOperandType b)
    

    Then, you'd have just to define your custom operator as in the following example:

    define operator(bool, myOr, bool, bool) { // Arguments are the return type, the name of the operator, the left operand type and the right operand type, respectively
        return a || b;
    }
    
    #define myOr  // Finally, you have to define a macro to avoid to put the < and > operator at the start and end of the operator name
    

    Once a time you've set your operator up, you can use it as a predefined operator:

    bool a = true myOr false;
    // a == true
    

提交回复
热议问题