你会禁止我从这个容器设计和使用?

时间:2013-07-03 13:56:24

标签: c++ arrays class templates containers

#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();
}

1 个答案:

答案 0 :(得分:1)

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

请改用std::array。即使您不能使用C ++ 11(其中引入了array),您也应该使用已经设计,构建和测试的内容,如std::vector