Reputation: 51
I have read some code about graph. But I have a question about template in C++.
typedef int intT;
template <class intT>
struct edge {
intT u;
intT v;
edge(intT f, intT s) : u(f), v(s) {}
};
template <class intT>
struct edgeArray {
edge<intT>* E;
intT numRows;
intT numCols;
intT nonZeros;
void del() {free(E);}
edgeArray(edge<intT> *EE, int r, int c, int nz) :
E(EE), numRows(r), numCols(c), nonZeros(nz) {}
edgeArray() {}
};
this code equals
struct edge {
int u;
int v;
edge(int f, int s) : u(f), v(s) {}
};
...
And why is the template<class int>
in this code ?
what is the difference between template<class T=int>
and template<class int>
?
There are two intT
, one is typedef int intT
, the other one is template< class intT>
, the scope of intT
is different ??
update:
The name of a template parameter hides the same name from the outer scope for the duration of its own:
typedef int N;
template< N X, // non-type parameter of type int
typename N, // scope of this N begins, scope of ::N interrupted
template<N Y> class T // N here is the template parameter, not int
> struct A;
https://en.cppreference.com/w/cpp/language/scope
Upvotes: 1
Views: 308
Reputation: 11340
And why is the
template<class int>
in this code ?
We can only guess here. Probably someone designed edge
and edgeArray
to hold values of type int
(the builtin int
!), then wanted to use templates instead and thought to be clever by naming the template parameter int
. But, surprise, this doesn't compile since int
is a keyword.
what is the difference between
template<class T=int>
andtemplate<class int>
?
template<class T=int>
declares a template with one template parameter called T
that defaults to int
. That means you can omit the template parameter and it will become int
by default.
template<class int>
on the other hand declares a template with one template parameter named int
. As mentioned above this doesn't compile.
Upvotes: 6