【问题标题】:How to access different members of class by using Traits pattern如何使用 Traits 模式访问类的不同成员
【发布时间】:2011-10-19 22:45:24
【问题描述】:

我有一个包含多个对象向量的类:

struct ComponentA
{
 public:
   methodA1();
   float data1;
   ...
};
struct ComponentB
{
   ...
};
struct ComponentC
{
   ...
};
struct ComponentD
{
   ...
};

class Assembly
{
    vector<ComponentA> As;
    vector<ComponentB> Bs;
    vector<ComponentC> Cs;
    vector<ComponentD> Ds;
};

我想使用特征并定义一个可以返回对成员的引用的函数,如下所示:

template< int T >
struct ComponentTraits;

template<>
ComponentTraits<TYPEA>
{
    typedef vector<ComponentA> data_type;
}
....
template< int T >
ComponentTraits<T>::data_type getComp(const Assembly & myassy)
{
    ...
}

这样一个电话

getComp<TYPEA>(thisassy)

将返回对 As 的引用,以便我可以在向量级别进行操作并访问每个组件对象的方法和数据:

getComp<TYPEA>(thisassy).push_back(newcomponentA);
getComp<TYPEA>(thisassy).back().methodA1();
getComp<TYPEA>(thisassy).front().data1 = 5.0;

谢谢,

和田

【问题讨论】:

    标签: c++ stl vector traits


    【解决方案1】:

    特征在这里不会做你想做的事。 C++ 缺乏说“给我找第一个属于 Y 类的 X 类成员”所需的内省支持。此外,特征旨在用于“告诉我更多关于 X 类型的信息”类型的操作。

    模板专业化可用于此,但工作量很大:

    template<class T>
    T& getComp<T>(Assembly& assy);
    
    template<>
    ComponentA& getComp<ComponentA>(Assembly& assy)
    { return assy.As;
    }
    
    template<>
    ComponentB& getComp<ComponentB>(Assembly& assy)
    { return assy.Bs;
    }
    
    template<>
    ComponentC& getComp<ComponentC>(Assembly& assy)
    { return assy.Cs;
    }
    
    template<>
    ComponentD& getComp<ComponentD>(Assembly& assy)
    { return assy.Ds;
    }
    

    或更短:

    template<class T>
    T& getComp<T>(Assembly& assy);
    
    #define SpecializeGetComp(T, field) template<> \
    T& getComp<T>(Assembly& assy) { return assy.field; }
    
    SpecializeGetComp(ComponentA, As)
    SpecializeGetComp(ComponentB, Bs)
    SpecializeGetComp(ComponentC, Cs)
    SpecializeGetComp(ComponentD, Ds)
    

    您可能还想阅读 Alexandrescu 的Modern C++ Design一书中的 Typelists(第 3 章)。您也许可以在类似工厂的模式中使用它们,但这远远超过 SO 答案真正适合的方式。

    【讨论】:

    • Mike,感谢您指出 C++ 中缺乏自省。我现在正在阅读 Typelists,希望能学到一两个关于模板的技巧。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-23
    • 2017-09-08
    • 2015-09-07
    • 2018-05-29
    • 1970-01-01
    • 2015-04-28
    相关资源
    最近更新 更多