使基类中的函数知道调用它的对象的类

问题描述

我的意思是在基类中定义一个函数,该函数能够打印调用它的对象的类,如果它是任何派生类,则正确解析。

例如这(预期)失败:

//======================================================
// 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();

产生

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

如果可能的话,我怎样才能在第二种情况下获得 level2
我的意思是不要在每个派生类中重新定义函数

解决方法

简单的解决办法,用type(this)替换type(*this)。 它有效,虽然我不知道如何解释。