Can somebody explain to me why the following works:
template<class T> class MyTemplateClass {
public:
T * ptr;
};
int main(int argc, char** argv) {
MyTemplateClass<double[5]> a;
a.ptr = new double[10][5];
a.ptr[2][3] = 7;
printf("%g\n", a.ptr[2][3]);
return 0;
}
But this doesn't:
class MyClass {
public:
double[5] * ptr;
// double(*ptr)[5]; // This would work
};
int main(int argc, char** argv) {
MyClass a;
a.ptr = new double[10][5];
a.ptr[2][3] = 7;
printf("%g\n", a.ptr[2][3]);
return 0;
}
Obviously there is more to template instantiation than just a textual replacement by the arguments to the template - is there a simple explanation of this magic?
For the latter the compiler (g++ 4.1.2) spits out the following error:
test.cxx:13: error: expected unqualified-id before '[' token
Where line 13 is the double[5] * ptr;
line.
The question is not:
"Why does the MyClass example fail? - because C++ doesn't allow Java style array declarations ;-)".
But is:
"Why does the MyTemplateClass example succeed?"