我已经看到建议使用此问题的解决方案
if( dynamic_cast<DerviedType1*>( base ) ){
// Do something
}
else if( dynamic_cast<DerviedType2*>( base ) ){
// Do something else
}
else if( dynamic_cast<DerviedType3*>( base ) ){
// Do another thing
}
// and so on
尽管功能强大,但该解决方案远非优雅,我希望有一个单行解决方案,即
decltype
或typeid
,这两个都不对我有帮助。我的具体问题如下。我有一个函数,它将一个指向基类实例的指针作为参数。然后,此函数将调用其中以派生类型为其参数的模板函数。例如。
void myFunc( Base *base )
{
myTemplateFunc<Derived>();
}
我想保持我的代码简单,没有
if
语句的 list ,但是我不确定该怎么做。应该注意的是,Base
对象本身不会传递给模板函数,只会传递它的类型。供引用,我正在寻找一些类似的东西
void myFunc( Base *base )
{
myTemplateFunc<decltype(base)>();
}
但这只会返回
Base
类型,在这里对我没有帮助。 最佳答案
另一种方法是多次调度
class Base
{
virtual void dispatch () = 0;
};
template <class T>
class BaseTpl : public Base
{
public:
void dispatch () {myTemplateFunc<T> ();}
};
然后
class DerviedType1 : public BaseTpl <DerviedType1>
{
};
和实际的用法
void myFunc( Base *base )
{
base->dispatch ();
}
关于c++ - 当可能有许多派生类型时,从基本类型的实例获取派生类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13159347/