带CRTP的C ++接口 - 在运行时键入dynamic_cast

时间:2018-06-17 12:48:03

标签: c++ templates crtp

我有这段代码:

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,我必须检查f1f2的所有可能组合并执行dynamic_cast,这可能是一个很长的列表,因为我有{{1} } ... Bar类。我无法直接调用method2,因为BarN没有IFoo

0 个答案:

没有答案