1

Problem is as follow: The following test throws huge amounts of compiler errors.

#include <vector>
using namespace std;

template<class T>
class test{
   vector<T> vec;
public:
   vector<T>::iterator begin();

};

template<class T>
vector<T>::iterator test<T>::begin(){
  return vec.begin();
}

int main(){

  test<float> testing;
  testing.begin();

}

Some Compiler errors:

 test.cpp(8): warning C4346: 'std::vector<T>::iterator' : dependent name is not a type
 test.cpp(8): error C2146: syntax error : missing ';' before identifier 'begin'
 test.cpp(13): error C2143: syntax error : missing ';' before 'test<T>::begin'

However, if you swap out the templated vector<T> for say, vector<float> its compiles just fine. For example:

template<class T>
class test{
   vector<T> vec;
public:
   vector<float>::iterator begin();

};

template<class T>
vector<float>::iterator test<T>::begin(){
   return vec.begin();
}

Any ideas as to why?

Steve Barna
  • 1,378
  • 3
  • 13
  • 23

3 Answers3

2

You need to add typename in two places:

typename vector<T>::iterator begin();

and

typename vector<T>::iterator test<T>::begin()

By adding typename, you are telling the compiler how to parse the code. Basically, by adding typename, you are telling the compiler to parse the declaration as a type.

Please read Where and why do I have to put the “template” and “typename” keywords? for an in-depth explanation.

Community
  • 1
  • 1
Jesse Good
  • 50,901
  • 14
  • 124
  • 166
1

You need to use the typename keyword to distinguish that vector<T>::iterator is referring to a scoped type, and not a scoped data or function member:

template<class T>
class test{
   vector<T> vec;
public:
   typename vector<T>::iterator begin();

};

template<class T>
typename vector<T>::iterator test<T>::begin(){
  return vec.begin();
}
jxh
  • 69,070
  • 8
  • 110
  • 193
-2

In C++ template classes, template member functions must have their body defined inside the class, because the template parameter does not exist outside of the class. The last two error look like what a compiler produces when unfamiliar context causes it to misinterpret perfectly valid syntax. Try moving the function body inside the class.

  • This isn't true. The definition of the template must be visible where the template is instantiated, but it doesn't have to be inside the class declaration. – jmk Oct 02 '12 at 17:24
  • Sorry. I was thinking of splitting the template across multiple files. My bad. – ValekHalfHeart Oct 03 '12 at 05:06
  • No worries, just wanted to clarify so nobody gets too confused. You might want to edit/delete your answer for clarity, though. – jmk Oct 03 '12 at 15:39