你能禁止我设计和使用这个集装箱吗

would you prohibit me from this container design and use?

本文关键字:集装箱 禁止      更新时间:2023-10-16
#include <iostream>
using namespace std;
//I want such a container that holds an array and don't want to expose array directly
template <size_t T>
class Container{
    public:
        Container(int in[]);
        int getValue(const unsigned int pos);
        //void setValue(const unsigned int pos,const int value);
        unsigned int getSize();
        /*...
        ...
        ...*/
        unsigned int theSize;
        int theArray[T];
};
template <size_t T>
Container<T>::Container(int in[]){
    theSize=T;
    for (unsigned int i=0;i<T;i++)
        theArray[i]=in[i];
}
template <size_t T>
int Container<T>::getValue(const unsigned int pos){return theArray[pos];}
template <size_t T>
unsigned int Container<T>::getSize(){
    return theSize;
}
//then I want to pass objects of this type around by address, but then to use that address //I have to do such design as follows, now would you prohibit me from doing this?
void someFunc(void * in){
    Container<1> * ptr=reinterpret_cast<Container<1> *>(in);
    unsigned int times=ptr->getSize();
    for (unsigned int i=0;i<times;i++)
        cout <<ptr->getValue(i)<<' ';
    cout <<'n';
}
int main(int argc,char ** argv){
    int araye[10]={1,2,3,4,5,6,7,8,9,10};
    Container<10> obj(araye);
    someFunc(&obj);
    cin.get();
}

是的,我会禁止您实现这个容器。你正在重新发明轮子,据我所知,没有理由这么做。

请改用std::array。即使您不能使用C++11(array就是在这里引入的),您也应该使用像std::vector这样已经设计、构建和测试过的东西。