简体   繁体   中英

Access non-type template parameters in constructor

I have a class that looks like this

#ifndef UNTITLED_FIXEDVECTOR_H
#define UNTITLED_FIXEDVECTOR_H

template<typename T, unsigned length>
class FixedVector {

public:
    FixedVector();

private:
    T data[];
};


#endif //UNTITLED_FIXEDVECTOR_H

But I can't in any way access length from its constructor:

#include "FixedVector.h"

FixedVector::FixedVector() {
    T[] data = new T[length]; //**NO LENGTH HERE!!!**
}

How can I access non-type template parameter from the constructor so that I can allocate data?

You can implement the body of your constructor in your header file :

template<typename T, unsigned length>
class FixedVector {

public:
    FixedVector()
    {
      data = new T[length];
    }

private:
    T* data;
};

Better yet, use std::array and not dynamic allocation if the length is known at compile time anyway, otherwise use std::vector .

You need to re-specify the template parameters

template <typename T, unsigned length>
FixedVector<T,length>::FixedVector() {
   data = new T[length];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM