1

When I try to compile template class, I got the following errors:

C.cpp: In member function 'void PeriodContainerAdvanced<T>::add()':
C.cpp:133: error: type/value mismatch at argument 1 in template parameter list for 'template<class _T1, class _T2> struct std::pair'
C.cpp:133: error:   expected a type, got 'std::map<int,T,std::less<int>,std::allocator<std::pair<const int, T> > >::iterator'
C.cpp:133: error: invalid type in declaration before ';' token

Class at C.h file: (Simplified)

template <class T>
class PeriodContainerAdvanced 
{
[skip]
    void add (); 
[skip]
}

C.cpp (Simplified):

template <class T>
void PeriodContainerAdvanced<T>::add()
{
[skip]
    std::pair<std::map< time_t, T >::iterator, bool> ret; // line 133 !
[skip]
}

And the similar error at other function when trying to define

std::map< time_t, T >::iterator it, it_start, it_end; // line 153

after this line compiler say:

C.cpp:153: error: expected `;' before 'it'
C.cpp:166: error: 'it_start' was not declared in this scope

How to fix it? thanks

2 Answers 2

9

That's a dependent name, you'll need to declare it as:

std::pair<typename std::map< time_t, T >::iterator, bool> ret;

Also, to avoid later linker errors, you should move template implementations to a file visible to all translation units that use that template - like the header where you define your template class.

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

Comments

6

First, need to put the add() implementation in the header file, or in a file included by the header. The compiler needs to see the code in order to instantiate the template for a given T.

Second, the source of the error you quote, you need to add a typename to tell the compiler you are talking about a type. std::map< time_t, T >::iterator could be interpreted as a value.

template <class T>
class PeriodContainerAdvanced {
  void add () {
    std::pair<typename std::map< time_t, T >::iterator, bool> ret;
    ....         ^
  }
};

3 Comments

its compile without "first" step, only with second. thanks. add defined at the header file like void add (); (see first message) and implemented at C.cpp
@abrahab OK, that is totally weird, unless your build system is doing something magic. Or maybe you haven't tried using it yet in an executable.
already used. seems gcc know that its implementation of the class function, because its defiled as: template <class T> void PeriodContainerAdvanced<T>::add() {..} at C.cpp . Interesting. Its like all others functions at separated .cpp file...

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.