C++模板,使用std迭代器的错误

abr*_*hab 1 c++ templates

当我尝试编译模板类时,我收到以下错误:

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
Run Code Online (Sandbox Code Playgroud)

Ch文件类:(简化)

template <class T>
class PeriodContainerAdvanced 
{
[skip]
    void add (); 
[skip]
}
Run Code Online (Sandbox Code Playgroud)

C.cpp(简体):

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

并且在尝试定义时其他函数的类似错误

std::map< time_t, T >::iterator it, it_start, it_end; // line 153
Run Code Online (Sandbox Code Playgroud)

在此行编译器之后说:

C.cpp:153: error: expected `;' before 'it'
C.cpp:166: error: 'it_start' was not declared in this scope
Run Code Online (Sandbox Code Playgroud)

怎么解决?谢谢

Luc*_*ore 9

这是一个依赖名称,您需要将其声明为:

std::pair<typename std::map< time_t, T >::iterator, bool> ret;
Run Code Online (Sandbox Code Playgroud)

此外,为了避免以后的链接器错误,您应该将模板实现移动到使用该模板的所有翻译单元可见的文件 - 例如您定义模板类的标题.


jua*_*nza 6

首先,需要将add()实现放在头文件中,或者放在头文件所包含的文件中.编译器需要查看代码才能实例化给定的模板T.

第二,你引用的错误的来源,你需要添加一个typename告诉编译器你正在谈论的类型.std::map< time_t, T >::iterator可以解释为一个值.

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