【问题标题】:C++ template which returns a different derived class based on template argument integer基于模板参数整数返回不同派生类的 C++ 模板
【发布时间】:2018-02-24 20:25:18
【问题描述】:

我不能完全弄清楚这样做的正确模式或习语,所以我很感激建议。

现在我有一个纯虚拟基类

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;
}

但是,这行不通,因为 Base 类是纯虚拟的。 接下来,我想也许可以对模板函数做一些特化

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

但是,这很愚蠢,因为这样我就必须在调用 getDerived 函数时明确声明该类。

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

【问题讨论】:

    标签: c++ templates


    【解决方案1】:

    您可以使用模板部分特化而不是将数字硬编码到类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>;
    

    【讨论】:

    • 我明白了。从语法的角度来看,这会起作用,但这真的会搞砸命名
    • 派生类都很长。它们适用于不同的传感器类型
    • 例如加速度计、陀螺仪等
    • 所以这样做会使代码阅读起来非常混乱。我可以放入一些 cmets,但我真的认为让类名具有描述性会更简洁。我会将这个添加到问题中。
    • 正如最初所说,您确实提出了一种有效的方法。
    猜你喜欢
    • 2021-09-26
    • 2021-04-13
    • 1970-01-01
    • 2012-07-02
    • 1970-01-01
    • 2015-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多