Template problem

V

Vespasian

I get the following compilation errors,

error C2057: expected constant expression
error C2133: 'tempArray' : unknown size
error C2466: cannot allocate an array of constant size 0

when compiling the following code:

template<class X> class Array {
public:
Array(int s) {size = s; }
int get_size(void) { return size; }
private:
int size;
};

#include <iostream>
#include <string>
#include "temp.h"
using namespace std;

template<class X> void Merge (Array<X>& values)
{
X tempArray[values.get_size()];
}

int main() {
int num;
cout << "How many words? ";
cin >> num;
Array<string> b(num);

Merge(b);

return 0;
}


Not sure why the errors occur. How do I fix this problem?

TIA,
ves
 
?

=?ISO-8859-15?Q?Juli=E1n?= Albo

Vespasian said:
template<class X> void Merge (Array<X>& values)
{
X tempArray[values.get_size()];
}


You can't do that in standard C++. The dimension of the array must be a
constante evaluable at compile time. Use a vector instead, for example.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top