如何查找,对象是由哪些类型组成的

How to find, from which Types is object composed of?

本文关键字:类型 对象 何查找 查找      更新时间:2023-10-16

好的,昨天我在这里发布了几乎相同的问题,但我不能根据我的需要修改答案。我不想搞乱其他的话题,所以我开始了一个新的。

所以,我有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();
}

(int只是举例)

所以我有一些模板魔法:

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上,让它更容易阅读。

谢谢!

EDIT:(在评论中提问)

我正在为AI构建系统,并希望在编译中解决尽可能多的事情我尽可能地拖延时间。在这种情况下,我正在构建运动行为系统。我的代码提供了许多类型的行为,如"Go to point","Evade from","避开障碍物"等等。这些行为在上面的例子中每个行为都有类似于"performBehavior"的方法其返回类型可与其他"performBehavior"组合使用。

所以我想把编译时的特定行为放在一起。如。只是A或A+C+D+F等

然后在我的更新中这样做:

如果行为由"Go to point"组成,那么"performBehaviorGoTo"

如果行为由"Evade from"组成,则"performBehaviorEvade"

这是一个非常简短的解释,但希望我已经表达了我的观点

可以通过函数重载实现:

template <typename Super, typename T1, typename T2> 
void doStuff(A<Super, T1, T2>& a) { a.doStaffA(); }
template <typename Super, typename T1, typename T2> 
void doStuff(B<Super, T1, T2>& b) { b.doStaffB(); }

然后:

// ...
void update()
{
    //this I want 
    //if( composed of A ) 
    //    m_cT.doStuffA();
    //if( composed of B ) 
    //    m_cT.doStuffB();
    doStuff(m_cT);
}

不清楚是否需要对A<B<...> >进行连锁调用。如果您这样做,那么将执行以下操作:

template <class T> 
void doStuff(T&) { /* do nothing */ }
template <typename Super, typename T1, typename T2> 
void doStuff(A<Super, T1, T2>& a) { 
    a.doStaffA(); 
    doStuff(static_cast<Super&>(a)); 
}
template <typename Super, typename T1, typename T2> 
void doStuff(B<Super, T1, T2>& b) { 
    b.doStaffB(); 
    doStuff(static_cast<Super&>(b)); 
}