Search code examples
c++classtemplates

How to use CONST instead of ENUM in a template class


So I'm trying to implement template class that holds a static array and I would like to use const int size as a parameter but the only way I can implement this class is by using enum technique for creating such an array.

template<class T>
class Stack
{
private:
    const int SIZE = 100;
    T data[SIZE];
public:

};


template<class T>
class StackTemplate {
    enum {ssize = 100};
    T stack[ssize];
    int top;
public:
    
};

The first implementation results in error in contrast to second one which is good. Is there any possible way to implement it using const int?

I get this error "C2597 illegal reference to non-static member 'Stack::SIZE' TheRevision" if I try to use const int instead of enum.


Solution

  • The compiler is hinting at a solution: just make SIZE static:

    template<class T>
    class Stack
    {
    private:
        static const int SIZE = 100;
        T data[SIZE];
    public:
    
    };
    

    Better yet, make it static constexpr int SIZE = 100;

    Or, perhaps even better, make SIZE a template argument:

    template<class T, size_t SIZE = 100>
    class Stack
    {
    private:
        T data[SIZE];
    public:
    
    };