Return type polymorphism in C-like languages

后端 未结 5 519
梦如初夏
梦如初夏 2021-01-17 14:46

Why don\'t we see C-like languages that allow for callables with polymorphism in the return type? I could see how the additional type inference would be a hurdle, but we hav

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-17 15:45

    In C++ you can do this with classes to a large extent. For example, say I have a data type that is routinely converted to ASCII on input and output;

    typedef char* pchar;
    
    class   MyType
    {
    public:
    
     operator pchar() { return(ConvertToASCII()); }
     MyType& operator=(char* input) { ConvertFromASCII(input); return(*this); }
    
     pchar ConvertToASCII();
     void ConvertFromASCII(pchar ASCII);
    }
    

    This type of thing is often used in C++ frameworks. For example, have a look at the implmentation of the MFC CString class. IMHO, it is a very useful tool, albeit dangerous in certain circumstances.

提交回复
热议问题