Saurav Sahu Saurav Sahu - 3 years ago 92
C++ Question

Why does "ClassName::MemberFunction" defined outside class give error?

Somehow I am not able to understand this answer.

Why can't we have a simple nested name specifier (for example

Foo::Foo(){}
instead of having a more verbose
Foo<T>::Foo(){}
), even when the template declaration is repeated right before the member function definition.

Answer Source

The subtlety is that in

template<class T>
int VisitedSet::getSize() {
   return vec.size();
}

the C++ compiler would not know yet what T applies to. When you're working inside the class definition for VisitedSet, you can use VisitedSet::... unambiguously, but outside the does not work.

When you're outside the class definition, the syntax requires that you tell the compiler what the template parameters are using the tempate<class T> syntax, and then that you tell the compiler where they apply.

In this case, that may seem ambiguous, but consider the following nested case:

template<class T>
class Foo {
   template<class R>
   class Bar {
      int getSize();
   };
};

Then it's more obvious why you need to be specific:

template<class X, class Y>
int Foo<Y>::Bar<X>::getSize() { ...

and

template<class A, class B>
int Foo<A>::Bar<B>::getSize() { ...

are both valid.

So that's why you need

template<class T>
int VisitedSet<T>::getSize() {
   return vec.size();
}

even in the simpler case shown in the answer you link to.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download