好的,昨天我在这里发布了几乎相同的问题 ,但我无法根据我的需要修改答案(工作)......我不想弄乱另一个话题,所以我开始了新的话题。
所以,我有 2 个(实际上大约 15 个)结构,它们可以组成一个对象
class MyBase{};
template <typename Super, typename T1, typename T2>
struct A : public Super
{
void doStuffA() { cout<<"doing something in A"; }
};
template <typename Super, typename T1, typename T2>
struct B : public Super
{
void doStuffB() { cout<<"doing something in B"; }
};
然后我有:
template <typename ComposedType, typename T1, typename T2>
class Combined
{
ComposedType m_cT;
public:
Combined(const ComposedType & c) : m_cT(c) { }
typedef A<null, T1, T2> anull;
typedef B<null, T1, T2> bnull;
void update()
{
typedef typename split<ComposedType>::Ct Ct;
typedef typename split<ComposedType>::At At;
//this I want
if( composed of A )
m_cT.doStuffA();
if( composed of B )
m_cT.doStuffB();
}
};
我想像这样使用它:
int main()
{
typedef A<B<MyBase,int,int>,int,int> ComposedType1;
typedef B<MyBase,int,int> ComposedType2;
ComposedType1 ct1;
ComposedType2 ct2;
Combined<ComposedType1, int, int> cb1(ct1);
cb1.update();
Combined<ComposedType2, int, int> cb2(ct2);
cb2.update();
}
(整数仅用于示例目的)
所以我有一些模板魔法:
struct null{};
template<typename>
struct split
{
typedef null Ct;
typedef null At;
};
template<template<typename> class C, typename T>
struct split<C<T> >
{
typedef C<null> Ct; //class template
typedef T At; //argument type
};
template<template<typename> class C>
struct split<C<MyBase> >
{
typedef C<null> Ct; //class template
typedef MyBase At; //argument type
};
但我不能让它工作:(
我知道有很多代码,但这实际上是最小的示例...我已将此代码发布到ideone,以使其更好地阅读。
谢谢!
编辑:(在评论中提问)
我正在为 AI 构建系统,并希望在编译时尽可能多地解决问题。在这种情况下,我正在构建运动行为系统。我的代码提供了许多类型的行为,如“前往点”、“避开”、“避开障碍物”等。这些行为在上面的示例中被称为 A a、B。每个行为都有类似“performBehavior”的方法及其返回类型可以与其他“performBehavior”组合。
所以我想在编译时把特定的行为放在一起。例如。只是 A 或 A+C+D+F 等...
然后在我的更新中执行以下操作:
如果行为由“Go to point”组成,则比“performBehaviorGoTo”
如果行为由“Evade from”组成,则比“performBehaviorEvade”
...
这是非常简短的解释,但希望我已经表达了我的观点