user1034592
user1034592

Reputation: 1

confused with template class in C++

I know that the template class definitions is like:

template <class TYPE>
class cars{
   public:
   TYPE myCar;
}

but somewhere I encountered to this piece of code:

template <class T>
class polynomialT {

    ...

}
************************************** 
class GFNUM2m {

...
}
**************************************
template class polynomialT<GFNUM2m>;

the last line is vague for me? any one knows what's up? is it an object of polynomialT class?(it seems not because it has no name) is it template?(it seems a duplicate because it has been templated once)

Upvotes: 2

Views: 153

Answers (5)

K-ballo
K-ballo

Reputation: 81349

template class polynomialT<GFNUM2m>;

Is a request to explicitly instantiate the template class polynomialT with GFNUM2m, including instantiating all its non-template functions.

Some cases when this is needed are:

  • When you want to avoid multiple template instantiation (that then get purged by the linker);
  • When you want to make sure that the full template can be instantiated even for those (non-template) functions not called;
  • When you want to provide template definitions within a .cpp file;

Upvotes: 5

sehe
sehe

Reputation: 392911

In fact, it is _explicit template instantiation. Use this to get the compiler to generate all (non-nested-template) members of the template class. This is convenient sometimes when linking externally to templated code, to prevent duplication of object code or missing externals (when methods get inlined).

Template specializations seem similar, but require template<> to announce the specialization of an already-declared template. Also, they would define an alternative class definition for that specific template parameter (as @rerun mentions).

Now, on the crosspoint of those, you could see

template<> class polynomialT<GFNUM2m>;

Which IS, in fact, a forward declared template specialization. This would serve to prevent the compiler from auto-instantiating the class template for that type parameter during the rest of the translation unit.

Upvotes: 0

Michael Price
Michael Price

Reputation: 8968

The last line is a forward declaration of the polynomialT class template with a template parameter of GFNUM2m, which also instantiates the template class.

Upvotes: -1

Fatih Donmez
Fatih Donmez

Reputation: 4347

it means template in the class polynomialT is now GFNUM2m class.

Upvotes: -2

Ruggero Turra
Ruggero Turra

Reputation: 17670

the last line is equivalent to:

class polynomialT {
  protected:
  GFNUM2m *coeff;                   // array of coefficients (? see below)
  int degree;
  ...

}

GFNUM2m *coeff is not an array, is simply a pointer to a GFNUM2m variable. Array and pointer are linked in some way, for example you can allocate dynamically an array with coeff = new GFNUM2m[10], but it is discouraged.

Upvotes: 1

Related Questions