【发布时间】: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 函数时明确声明该类。
所以我觉得要么我遗漏了一些简单的东西,要么我使用的整个方法都是错误的。你们有什么建议吗?
【问题讨论】: