如何基于C ++中的参数初始化类的成员?

I want to implement a class that uses N-dimensional vectors (from the mathematical point of view). I'm using Vec objects from the opencv library, and their signature looks like this: Vec<typename _Tp, int cn> where cn is the number of elements inside that vector. I must provide a constant for the cn parameter.

我希望我的班级看起来像这样:

class MyClass
{
private:
    Vec<float, dim> m_center;
    vector<Vec<float, dim>> m_points;
// ...
}

and I want to be able to initialize dim dinamically, that is create a MyClass object that has its dim set to whatever number I want. How can I correctly approach this problem in C++?

评论
  • 伊筱沫
    伊筱沫 回复
    template <typename T, int N=1>
    class Vec
    {
    public:
        Vec()
        {
            auto deleter = [](T* t) { delete[] t; };
    
            unique_ptr <T, decltype(deleter)> test(new T[N], deleter);
        }
        string getType()
        {
            return typeid(T).name();
        }
        int getSize()
        {
            return sz;
        }
    
    private:
        T t;
        int sz = N;
    };
    
    template<int dim = 1>
    class MyClass
    {
    public:
        MyClass()
        {
            m_points.resize(5);
        }
        Vec<float, dim> getCenter()
        {
            return m_center;
        }
    
        vector<Vec<float, dim>> getPoints()
        {
            return m_points;
        }
    
    private:
        Vec<float, dim> m_center;
        vector<Vec<float, dim>> m_points;
    };
    

    测试代码:

    int main()
    {
        MyClass<10> my;
    
        cout << "center size = " << my.getCenter().getSize() << endl;
        cout << "center type =" << my.getCenter().getType().c_str() << endl;
    
        cout << "points size" << my.getPoints().size() << endl;
    
        cout << "first point size = " << my.getPoints()[0].getSize() << endl;
        cout << "first point type =" << my.getPoints()[0].getType().c_str() << endl;
    
        std::cout << "Hello World!\n"; 
    }
    

    输出: 中心大小= 10 中心类型=浮动 点数5 第一点大小= 10 第一点类型=浮动 你好,世界!