Instantiating a template class with typename itself being a template class
I want to know how should I initialize a template class where the typename itself is having templates. The class that I want to initialize is as follows:
typedef TVec<TPair <TInt, TLst<TInt>> > TMyType;
I am just instantiating my object with the default constructor (i.e. empty parenthesis) and would like to know will it also instantiate the TPair and TLst types that are within the typename? For example, can I instantiate simply as below?
TMyType myClass();
Or how should I instantiate TMyType
object?
Below I have provided the definition of the template classes as they are in the library along with their default constructors.
The definition of the template classes with their default constructors are as follows:
Vector of TVals
template <class TVal> class TVec{ public: typedef TVal* TIter; protected: int MxVals; int Vals; TVal* ValT; public: TVec(): MxVals(0), Vals(0), ValT(NULL){} ... };
Pair of TVals
template <class TVal1, class TVal2> class TPair{ public: TVal1 Val1; TVal2 Val2; public: TPair(): Val1(), Val2(){} ... };
List
template <class TVal> class TLst{ public: typedef TLstNd<TVal>* PLstNd; private: int Nds; PLstNd FirstNd; PLstNd LastNd; public: TLst(): Nds(0), FirstNd(NULL), LastNd(NULL){}
Integer
class TInt{ public: int Val; public: TInt(): Val(0){} TInt(const int& _Val): Val(_Val){} ... };
A Node in List
template <class TVal> class TLstNd{ public: TLstNd* PrevNd; TLstNd* NextNd; TVal Val; public: TLstNd(): PrevNd(NULL), NextNd(N开发者_如何学JAVAULL), Val(){} ... };
TMyType myClass();
does not instantiate any object, instead it declares a function prototype of function myClass
which returns a type TMyType
. You should omit the parenthesis and use TMyType myClass;
.
You can simply instantiate your object with the default constructor. However using empty paranteses (TMyType myClass();
) won't do this. This will be parsed as a function declaration (function named myClass
, which takes no arguments and returns an object of type TMyType
). This will most likely lead to a compiler error somewhere down the line when trying to use the variable. To default construct a variable you should omit the parentheses:
TMyType myClass;
This is different from default constructing a anonymous object of type TMyType, which would need the parantheses (so you can do TMyType()
, but not TMyType myVar();
).
I ran the following code:
typedef TVec<TPair<TInt,TLst<TInt>>> TMyType;
TMyType obj(10,0);
TInt val1;
TLst<TInt> val2;
for (int i=0; i<10; i++)
{
obj[i].GetVal(val1,val2);
printf("%d %i\n",val1,val2.Len());
}
return 0;
The output was as follows:
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
But I am instantiating the object obj with MxVals = 10
and Vals = 0
and it works fine.
精彩评论