C++本身可以一个对象的多态调用接口,
需要实现根据多个对象对函数调用动作进行分派的技术
多重方法和多重分派
template
<
class Executor,
class BaseLhs,
class BaseRhs= BaseLhs,
class TypesRhs=TypesLhs,
typename ResultType=void
>
class StaticDispatcher
{
typedef typename TypesLhs::Head Head;
typedef typename TypesLhs::Tail Tail;
public :
static ResultType Go(BaseLhs& lhs,BaseRhs& rhs,Executor exec)
{
if(Head *p1 =dynamic_cast<Head*>(&lhs))
{
return StaticDispatcher<Executor,BaseLhs,NullType,BaseRhs,TypesRhs>::DispatchRhs(*p1,rhs,exec);
}
else
{
return StaticDispatcher<Executor,BaseLhs,Tail,BaseRhs,TypesRhs>::Go(lhs,rhs,exec);
}
}
template<class SomeLhs>
static ResultType DispatchRhs(SomeLhs &lhs,BastRhs& rhs,Executor exec)
{
typedef typename TypesRhs::Head Head;
typedef typename TypesRhs::Tail Tail;
if(Head*p2 = dynamic_cast<Head*>(&rhs))
{
return exec.fire(lhs,*p2);
}
else
{
return StaticDispatcher<Executor,SomeLhs,NullType,BaseRhs,Tail>::DispatchRhs(lhs,rhs,exec);
}
}
需要实现根据多个对象对函数调用动作进行分派的技术
多重方法和多重分派
template
<
class Executor,
class BaseLhs,
class BaseRhs= BaseLhs,
class TypesRhs=TypesLhs,
typename ResultType=void
>
class StaticDispatcher
{
typedef typename TypesLhs::Head Head;
typedef typename TypesLhs::Tail Tail;
public :
static ResultType Go(BaseLhs& lhs,BaseRhs& rhs,Executor exec)
{
if(Head *p1 =dynamic_cast<Head*>(&lhs))
{
return StaticDispatcher<Executor,BaseLhs,NullType,BaseRhs,TypesRhs>::DispatchRhs(*p1,rhs,exec);
}
else
{
return StaticDispatcher<Executor,BaseLhs,Tail,BaseRhs,TypesRhs>::Go(lhs,rhs,exec);
}
}
template<class SomeLhs>
static ResultType DispatchRhs(SomeLhs &lhs,BastRhs& rhs,Executor exec)
{
typedef typename TypesRhs::Head Head;
typedef typename TypesRhs::Tail Tail;
if(Head*p2 = dynamic_cast<Head*>(&rhs))
{
return exec.fire(lhs,*p2);
}
else
{
return StaticDispatcher<Executor,SomeLhs,NullType,BaseRhs,Tail>::DispatchRhs(lhs,rhs,exec);
}
}
}
总结,泛型是C++的一部分,程序中依赖程度和运用程度取决程序员本身,泛型是可替代的一项技术,不可替代的是template