这是场景:
class Base {
public:
typedef Base type;
};
class Derived: public Base {
public:
typedef Derived type;
};
我想要类似的东西:
int main() {
Base * bs = new Derived();
decltype(*bs)::type newvar;
}
如何在不使用静态/动态转换的情况下执行上述操作来获取 Derived 类的类型?
这是场景:
class Base {
public:
typedef Base type;
};
class Derived: public Base {
public:
typedef Derived type;
};
我想要类似的东西:
int main() {
Base * bs = new Derived();
decltype(*bs)::type newvar;
}
如何在不使用静态/动态转换的情况下执行上述操作来获取 Derived 类的类型?
在您的代码中,*bs实际上有两种类型:静态类型,即声明它的类型,即Base. 另一种类型是动态类型,在您的情况下,它是它实际指向的对象的类型Derived。静态类型是编译时唯一已知的类型,并且不能更改。TMP、普通函数调用和所有模板内容都发生在编译时,因此也只有静态类型适用于这些。
使用动态类型的唯一方法是向编译器明确说明,这意味着调用虚函数或使用dynamic_cast.
你说你想要“类似”你展示的代码——你想用它来完成什么?我很确定答案将是“如果您想根据动态类型做事,请使用虚函数”,因为dynamic_cast通常不是一个真正的选择。
不,你不能那样做。
C++ 是静态类型语言,这意味着必须在编译时确定类型。
在示例bs中不知道它指向的对象类型。
请参阅下面的场景以使其更清晰:
Base * bs = (bool)? new Base() : new Derived();
你必须依靠virtual机制或dynamic_cast实现你的最终目的。