以编程方式进行C++编译:可以完成吗?

Geo*_*Geo 5 c++ casting

假设我有一个Base类和几个Derived类.有没有办法将对象强制转换为派生类之一,而无需编写如下内容:


string typename = typeid(*object).name();
if(typename == "Derived1") {
   Derived1 *d1 = static_cast< Derived1*>(object);
}
else if(typename == "Derived2") {
   Derived2 *d2 = static_cast < Derived2*>(object);
}
...
else {
  ...
}
Run Code Online (Sandbox Code Playgroud)

S.L*_*ott 22

别.

阅读多态性.几乎每个"动态演员"情况都是难以实现的多态性的一个例子.

无论你在动态演员表中做出什么决定都已经完成了.只需将实际工作委托给子类.

你遗漏了你的例子中最重要的部分.有用的多态工作.

string typename = typeid(*object).name();
if(typename == "Derived1") {
   Derived1 *d1 = static_cast< Derived1*>(object);
   d1->doSomethingUseful();
}
else if(typename == "Derived2") {
   Derived2 *d2 = static_cast < Derived2*>(object);
   d2->doSomethingUseful();
}
...
else {
  ...
}
Run Code Online (Sandbox Code Playgroud)

如果每个子类都实现了doSomethingUseful,那么这就简单得多了.而且是多态的.

object->doSomethingUseful();
Run Code Online (Sandbox Code Playgroud)


fhe*_*fhe 9

您可以使用dynamic_cast和测试NULL,但我强烈考虑重构代码.

如果你需要特定于子类的处理,模板方法可能会有所帮助,但不知道你想要实现什么,它只是一个模糊的猜测.


mar*_*jne 5

Derived1* d1 = dynamic_cast< Derived1* >(object);
if (d1 == NULL)
{
    Derived2* d2 = dynamic_cast< Derived2* >(object);
    //etc
}
Run Code Online (Sandbox Code Playgroud)

我的smartpointer类型有以下方法,模拟C#'是'和'as':

template< class Y > bool is() const throw()
    {return !null() && dynamic_cast< Y* >(ptr) != NULL;}
template< class Y > Y* as() const throw()
    {return null() ? NULL : dynamic_cast< Y* >(ptr);}
Run Code Online (Sandbox Code Playgroud)