2021年4月30日星期五

Make a function in the base class aware of the class of the object calling it

I mean to define a function in the base class that is able to print the class of the object calling it, resolving correctly if it is of any derived class.

For instance this (expectedly) fails:

//======================================================  // demangle is copied from https://stackoverflow.com/a/4541470/2707864  #include <string>  #include <typeinfo>    std::string demangle(const char* name);    template <class T>  std::string type(const T& t) {      return demangle(typeid(t).name());  }    //======================================================  // Class definition  class level1 {  public:      virtual void whoami() const {          std::cout << "I am of type " << type(this) << std::endl;      }  };    class level2 : public level1 {  };    //======================================================  // Testing    level1 l1;  l1.whoami();  level2 l2;  l2.whoami();  

which produces

I am of type level1 const*  I am of type level1 const*  

How can I get level2 in the second case, if possible at all?
I mean to not redefine the function in each derived class.

https://stackoverflow.com/questions/67342085/make-a-function-in-the-base-class-aware-of-the-class-of-the-object-calling-it May 01, 2021 at 09:14AM

没有评论:

发表评论