Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

templates

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?

like image 502
JamesBondage Avatar asked Oct 16 '25 18:10

JamesBondage


1 Answers

You need it because Bar is not a class, it's a template. Bar<T> is the class.

like image 82
Some programmer dude Avatar answered Oct 19 '25 09:10

Some programmer dude