Using an int as a template parameter that is not known until run-time

后端 未结 5 1535
谎友^
谎友^ 2021-01-02 19:04

I am trying to use an integer as a template parameter for a class. Here is a sample of the code:

template< int array_qty > 
class sample_class {

    p         


        
5条回答
  •  清歌不尽
    2021-01-02 19:33

    I'm a little late, but here's my suggestion. I'm guessing the main problem with vectors for you is that they allocate a larger capacity than what you need in order to support dynamic growth. So, can't you write your own simple array class?

    template 
    class Array {
        private: 
            T* data; 
            unsigned size; 
        public: 
            Array(unsigned size) {
                data = new T[size]; 
                this->size = size; 
            }
            T& operator[](int i) {
                return data[i]; 
            }
            T operator[](int i) const {
                return data[i]; 
            }
    
            // Depending on your needs, maybe add copy constructor and assignment operator here.
            ...
    
            unsigned size() {
                return size; 
            }
    
            ~Array() {
                delete [] data; 
            }
    }
    

    From what I know, I believe this should be just as fast as the STL array class. In addition, you can create Arrays with sizes unknown until run-time, the Array's memory is handled automatically when it is destroyed, and you don't have to instantiate a new class every time you create a new array with a different size (like you have to do for STL arrays).

提交回复
热议问题