Reputation: 3
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.
Upvotes: 0
Views: 55
Reputation: 13076
Make the size of your stack a template parameter too like this. (side notd I prefer not to use "C" style arrays)
#include <array>
template<typename T, std::size_t SIZE> // optionally make SIZE have a default value. E.g. std::size_t SIZE=100
class Stack
{
public:
constexpr std::size_t size() const noexcept
{
return data.size(); // OR return SIZE, but this shows the use of std::array
}
private:
std::array<T,SIZE> data;
};
int main()
{
Stack<int,100> stack;
static_assert(stack.size() == 100);
}
Upvotes: 1
Reputation: 85481
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:
};
Upvotes: 2