When does a template end?

c++

Solution

The scope of the template parameter ends with the scope of the templated subject:

template <class T>
class thatClass
{
   T a, b;
   thatClass (T x, T y) {a = x; b = y;}
}; // << ends here

template <class T>T aFunc(T one, T two)
{
   return one+two;
}  // << ends here

And why can't you just use the one template you declared for both classes and functions, so in this case, I could use the template parameter `T` for both the function `aFunc` and for the class definition?

You can't because template parameter scope is always bound to a class/struct or function definition. That's defined as such in the language.

One could think of templating a whole `namespace`, but that's not an available language feature, and I'm not sure if that would be a good idea at all.

As you seem to be confused I'll add some variations:

template <class T>
class thatClass
{
   T a, b;
   thatClass (T x, T y) {a = x; b = y;}
   // A member funcion that uses the same template parameter and accesses 
   // the class member variables
   T aFunc() { return a+b; }
   // A static member funcion that uses the same template parameter and
   // calculates the result from the parameters
   static T aStaticFunc(T one, T two) { return one+two; }
 };

Problem

When does a template end? Let's have a look at this code: ``` template <class T> class thatClass { T a, b; thatClass (T x, T y) {a = x; b = y;} }; template <class T>T aFunc(T one, T two) { return one+two; } ``` So when does `template <class T>` end? Does it always end after at the end of a class or function definition or what? And why can't you just use the one template you declared for both classes and functions, so in this case, I could use the template parameter `T` for both the function `aFunc` and for the class definition?

Original source