代码之家  ›  专栏  ›  技术社区  ›  bremen_matt

基于模板参数整数返回不同派生类的C++模板

  •  0
  • bremen_matt  · 技术社区  · 8 年前

    我不能很好地找出正确的模式或习惯用法来做这件事,所以我很感激你的建议。

    现在我有一个纯虚拟基类

    template<typename T, int size>
    class Base {
    
    public:
    
        virtual Eigen::Matrix<T, x_size, 1>
        doSomething(const Eigen::Matrix<T, x_size, 1> &x) = 0;
    
        ...
    

    我有一些派生类,对于 size 模板参数。例如,

    template<typename T>
    class Accelerometer : public Base<T, 4> { ...
    
    template<typename T>
    class Gyroscope : public Base<T, 5> { ...
    

    有很多这样的课程。他们都很不一样。

    编辑:我不想重命名这些类,因为这样做会使代码读起来非常混乱。

    在代码的其他地方,我有一个类,它包含对 Base 类对象:

    template<typename T, int size>
    class Other {
    private:
    
        Base<T, size> &base;
    
    public:
    
        Other(Base<T, size> &base) : base(base) {...
    

    比如,我可以说

    Other<T, 4> other4( Derived4<T>() );
    Other<T, 5> other5( Derived5<T>() );
    

    然而,在我的主代码中,我只需要一个 Other 例子理想情况下,我想这样做:

    const int size = 4;
    // TODO Initialize `other` with appropriate derived class. 
    Other<T,size> other( getDerived<size>() ) 
    

    其中 getDerived 函数将返回 Derived 适当大小的类。我不知道如何定义这样一个函数。我的第一个想法是这样做:

    template<int size>
    Base<size> getDerived() {
        return NULL;
    }
    

    然而,这是行不通的,因为基类是纯虚拟的。 接下来,我考虑对模板函数进行一些专门化

    template<DerivedType>
    DerivedType getDerived() {
        return NULL;
    }
    

    然而,这很愚蠢,因为这样我在调用 获取派生 作用

    所以我觉得要么我遗漏了一些简单的东西,要么我使用的整个方法都是错误的。你们有什么建议吗?

    1 回复  |  直到 8 年前
        1
  •  2
  •   llllllllll    8 年前

    您可以使用模板部分专门化,而不是将数字硬编码到类中 Derived4 , Derived5 的名称:

    template<class T, int N> struct Base {};
    
    template<class T, int N> struct Derived;
    
    template<class T>
    struct Derived<T, 4> : public Base<T, 4> {
        /* for Derived4 */
    };
    
    template<class T>
    struct Derived<T, 5> : public Base<T, 5> {
        /* for Derived5 */
    };
    
    template<class T, int N>
    Derived<T, N> getDerived();
    

    编辑:

    如果希望类名具有描述性,可以始终使用 using alias ,例如:

    template<class T> using Accelerometer = Derived<T, 4>;
    template<class T> using Gyroscope = Derived<T, 5>;