I'm sorry for my bad English, but it isn't my language.
I've done an exercise in C++11 for University:
This is a program for understanding Templates:
#include <iostream>
#include <cstdlib>
#include <ctime>
class matrix{
public:
matrix(int riga, int colonna){
this->riga=riga;
this->colonna=colonna;
}
matrix(){
this->riga=0;
this->colonna=0;
}
template <typename T> T crea(){
auto a = new<T>*(riga);
for(int i=0; i!=riga; ++i){
a[i]=new<T>(colonna);
}
}
private:
int riga, colonna;
}
using namespace std;
int main(){
auto v=crea<int>(5,10);
srand(time(nullptr));
for(int i=0, j=0; i!=5, j!=10; ++i, ++j){
v[i][j]=rand()%100+1;
}
for(int i=0, j=0; i!=5, j!=10; ++i, ++j){
cout<<v[i][j]<<endl;
}
return 0;
}
Thanks in advance.
[Edit - Added from comments]
This is compiler result:
m.cpp: In member function ‘T matrix::crea()’:
m.cpp:17:15: error: expected type-specifier before ‘<’ token
auto a = new<t>*(riga);
^
m.cpp:17:17: error: expected primary-expression before ‘>’ token
auto a = new<t>*(riga);
^
m.cpp:17:24: error: invalid type argument of unary ‘*’ (have ‘int’)
auto a = new<t>*(riga);
^
m.cpp:20:12: error: expected type-specifier before ‘<’ token
a[i]=new<t>(colonna);
^
m.cpp:20:14: error: expected primary-expression before ‘>’ token
a[i]=new<t>(colonna);
^
m.cpp: In function ‘int main()’:
m.cpp:31:9: error: ‘crea’ was not declared in this scope
auto v=crea<int>(5,10);
^
m.cpp:31:14: error: expected primary-expression before ‘int’
auto v=crea<int>(5,10);
[/Edit]
Update 2:
i've modified the code with this:
#include <iostream>
#include <cstdlib>
#include <ctime>
class matrix{
public:
matrix(){
this->riga=0;
this->colonna=0;
}
~matrix(){
}
template <typename T> T crea(){
auto a = new T*[riga];
for(int i=0; i!=riga; ++i){
a[i]=new T[colonna];
}
return a;
}
private:
int riga, colonna;
};
using namespace std;
int main(){
matrix c;
auto v=c.crea<int>();
srand(time(nullptr));
for(auto i=0, j=0; i!=5, j!=10; ++i, ++j){
v[i][j]=rand()%100+1;
}
for(auto i=0, j=0; i!=5, j!=10; ++i, ++j){
cout<<v[i][j]<<endl;
}
return 0;
}
and this is compiler result:
m.cpp: In function ‘int main()’:
m.cpp:34:6: error: invalid types ‘int[int]’ for array subscript
v[i][j]=rand()%100+1;
^
m.cpp:38:12: error: invalid types ‘int[int]’ for array subscript
cout<<v[i][j]<<endl;
^
m.cpp: In instantiation of ‘T matrix::crea() [with T = int]’:
m.cpp:30:21: required from here
m.cpp:19:10: error: invalid conversion from ‘int**’ to ‘int’ [-fpermissive]
return a;
^