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?

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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();
}

1 Comment

It is a member -- just a member type, not a member variable.
-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.

3 Comments

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.
Sorry. I was thinking of splitting the template across multiple files. My bad.
No worries, just wanted to clarify so nobody gets too confused. You might want to edit/delete your answer for clarity, though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.