Why do we need 'template <class T>' before implementing all templated class methods

  • A+

If we have a standard class:

class Foo {   public:     int fooVar = 10;     int getFooVar(); } 

The implementation for getFooVar() would be:

   int Foo::getFooVar() {        return fooVar;    } 

But in a templated class:

template <class T> class Bar {   public:     int barVar = 10;     int getBarVar(); } 

The implementation for getBarVar() must be:

template <class T> int Bar<T>::getBarVar(){    return barVar(); } 

Why must we have the template <class T> line before the function implementation of getBarVar and Bar<T>:: (as opposed to just Bar::), considering the fact that the function doesn't use any templated variables?


Bar itself is a template, as the other answers said.

But let's now assume that you don't need it, after all, you specified this, and I added another template argument:

template<typename T1, typename T2> class Bar {     void something(); }; 


template<typename T1, typename T2> void Bar<T1, T2>::something(){} 

And not:

void Bar::something(){} 

What would happen if you wanted to specialize your implementation for one type T1, but not the other one? You would need to add that information. And that's where this template declaration comes into play and why you also need it for the general implementation (IMHO).

template<typename T> void Bar<T, int>::something(){} 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: