Reputation: 6842
How can I initialize an array, s
of template type T
in my constructor Stack()
? This might be a really simple question, but I don't know much of c++. I get this error when compiling (GNU GCC):
error: incompatible types in assignment of 'double*' to 'double [0]'
This is how I'm initializing the Stack
object in my main.cpp
:
Stack<double> stack;
And here is my Stack.h
file (the implementation is included):
#pragma once
#include <iostream>
using namespace std;
template <class T>
class Stack
{
public:
Stack();
private:
T s[];
int N;
};
template <class T>
Stack<T>::Stack() {
s = new T[5];
}
Upvotes: 0
Views: 1845
Reputation: 29724
First, the size of array put on stack has to be known at compile time, so
T s[];
shoud read for instance
T s[10];
Second array of T
is different type then T*
return by new
.
Solution:
class Stack
{
public:
Stack();
~Stack() { delete[] s_;} // to avoid memory leak delete the array
private:
T* s;
int N;
};
template <class T>
Stack<T>::Stack() {
s = new T[10];
}
usage:
int main() {
Stack<int> s;
return 0;
}
Even better, make the size of array a template parameter:
template <class T, size_t N>
class Stack
{
public:
Stack();
~Stack() { delete[] s_;} // to avoid memory leak delete the array
private:
T* s_;
int N_;
};
template <class T, size_t N>
Stack<T,N>::Stack() : N_( N) {
s_ = new T[N_];
}
usage:
int main() {
Stack< int,10> s;
return 0;
}
Use templates, make standard container a template parameter:
template <class T, size_t N, template<class T,
class = std::allocator<T> > class C >
class Stack
{
public:
Stack();
~Stack() {}
private:
C<T> s_;
int N_;
};
template <class T, size_t N, template<class T,
class = std::allocator<T> > class C >
Stack<T,N,C>::Stack() : N_( N) {
s_.resize( N_);
}
usage:
int main() {
Stack< int,10,std::vector > s;
return 0;
}
Upvotes: 1
Reputation: 18218
One alternative is to give the array size as what is called a non-type template parameter (I'm assuming N is meant to represent the current stack size):
template <class T, int size>
class Stack
{
public:
Stack() : N(0) {}
private:
T s[size];
int N;
};
You could use it as follows:
Stack<double, 5> myStack;
Upvotes: 1
Reputation: 310910
Change
//...
private:
T s[];
to
//...
private:
T *s;
This declaration
private:
T s[];
is not C++ compliant. The size of the array shall be a constant expression. Moreover you declared an array but use it as a pointer in the constructor
s = new T[5];
Or use std::vector
instead of the manually allocated array.
Upvotes: 2