我有这段代码:
struct IFoo
{
std::string type;
virtual void foo() = 0;
};
template <typename T>
struct Foo1 : public IFoo
{
void foo() override { printf("foo"); }
void iBar() { static_cast<T *>(this)->bar(); }
};
struct Bar : public Foo1<Bar>
{
Bar() { this->type = "Bar"; }
void bar() { printf("bar"); }
};
void method(IFoo * f1, IFoo * f2)
{
if ((f1->type == "Bar") && (f2->type == "Bar")){
method2(dynamic_cast<Bar *>(f1), dynamic_cast<Bar *>(f2));
}
//how to call method2 more friendly, then if-else of all possible cases?
};
template <typename T, typename F>
void method2(T * b1, F * b2){
//here I want to call bar()
};
int main(){
IFoo * b1 = new Bar();
IFoo * b2 = new Bar();
method(b1, b2);
return 0;
};
有没有办法,怎样在dynamic_cast
更多地“动态地”进行method
?目前,如果我想调用method2,我必须检查f1
和f2
的所有可能组合并执行dynamic_cast
,这可能是一个很长的列表,因为我有{{1} } ... Bar
类。我无法直接调用method2,因为BarN
没有IFoo
。