it is possible to change return type when override a virtual function in C++?

后端 未结 6 1401
醉梦人生
醉梦人生 2020-12-16 03:34

I encounter a problems about override virtual functions, in fact,it is about hessian (a web service protocol).

it has a base class Object, and some derived classes :

6条回答
  •  鱼传尺愫
    2020-12-16 04:06

    Regarding @MerickOWA comment, here's another solution, that does not requires any additional template mechanism.

    Since you intended to have a virtual "value()" method that you needed to implement in all classes, I've extended the idea (usually, in these kind of framework, you've plenty of similar "basic" methods, so I've used a macro to write them for me, it's not required, it's just faster and less error prone.

    #include 
    #include 
    #include 
    
    struct Object
    {
       std::string toString() const { std::ostringstream str; getValue(str); return str.str(); }
       virtual void getValue(std::ostringstream & str) const { str<<"BadObj"; }
    };
    
    // Add all the common "basic & common" function here
    #define __BoilerPlate__     basic_type value; void getValue(std::ostringstream & str) const { str << value; }
    // The only type specific part
    #define MAKE_OBJ(T)         typedef T basic_type;      __BoilerPlate__
    
    struct Long : public Object
    {
       MAKE_OBJ(long long)
       Long() : value(345) {}
    };
    
    struct Int : public Object
    {
       MAKE_OBJ(long)
       Int() : value(3) {}
    };
    
    int main()
    {
        Object a;
        Long b;
        Int c;
        std::cout<

    Obviously, the trick is in the std::ostringstream classes that's accept any parameter type (long long, long, etc...). Since this is standard C++ practice, it should not matter.

提交回复
热议问题