接口作为模板参数

时间:2017-04-03 20:11:52

标签: c++ interface

我有一个直方图类的构造函数:

Histogram(float start, float end, float bin_size, std::vector<BinnableObject<T>*>* data);

关注界面

template<typename T>
class BinnableObject
{
public:
    virtual T getBinnableObject() = 0;
};

我有一个实现此接口的课程Ring

template<class T>
class Ring : BinnableObject<T>
{
public:
    Ring(Point<T> c, T r)
    {
        m_center = c;
        m_radius = r;
    }
    Point<T> m_center;
    T m_radius;

    T getBinnableObject()
    {
        return m_radius;
    }
};

有没有办法可以使用Rings向量调用直方图构造函数?

Histogram<float> h(0.0f, 1.0f, 0.1f, &data.m_rings);

其中&data.m_ringsstd::vector<Ring<float>*>

MCVE低于

#include <vector>

template<typename T>
class BinnableObject
{
public:
    virtual T getBinnableObject() = 0;
};



template<class T>
class Ring : public BinnableObject<T>
{
public:
    T m_radius;
    T getBinnableObject()
    {
        return m_radius;
    }
};


template <typename T>
class Histogram
{
public:
    Histogram(float start, float end, float bin_size, std::vector<BinnableObject<T> >* data) {};
};


int main()
{
    std::vector<Ring<float>*> rings;
    Histogram<float> h(0.0f, 1.0f, 0.1f, &rings);
}

1 个答案:

答案 0 :(得分:2)

您遇到的问题与std::vector<Ring<T>>std::vector<BinnableObject<T>>无关,而与Ring BinnableObject的继承无关。

然而,你能否将直方图设为模板化函数/构造函数?

即。

template<class T>
Histogram(float, float, float, std::vector<T>);