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

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

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

例如,这(预期)失败了:

//======================================================
// demangle is copied from 
#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
我的意思是不在每个派生的 class.

中重新定义函数

简单的解决方案,将type(this)替换为type(*this)。 它有效,虽然我不知道如何解释它。