实现嵌套在模板类中的类的成员函数

Implementing a member function of a class nested in a template class

本文关键字:成员 函数 嵌套 实现      更新时间:2023-10-16

我正在.cpp中实现模板成员函数,并了解所涉及的限制(一次只将此类模板化为一种类型)。 一切都很好,除了这种情况。 虽然我已经让嵌套类的构造函数工作,但我在使用任何其他嵌套类成员函数时遇到了问题。 作为参考,我正在使用VC++ 11进行编译。

在 .h 中:

template<typename T> class TemplateClass
{
 class NestedClass
 {
  NestedClass();
  bool operator<(const NestedClass& rhs) const;
 };
};

在.cpp:

//this compiles fine:
template<typename T>
TemplateClass<T>::NestedClass::NestedClass()
{
 //do stuff here
}
//this won't compile:
template<typename T>
bool TemplateClass<T>::NestedClass::operator<(const TemplateClass<T>::NestedClass& rhs) const
{
 //do stuff here
 return true;
}
template class TemplateClass<int>; //only using int specialization

编辑:这是错误,都指向operator<实现行

错误

C2059:语法错误:"const"
错误 C2065:"rhs":未声明的标识符
错误 C2072:"模板类::嵌套类::运算符<":函数
的初始化错误 C2470:"模板类::嵌套类::运算符<":看起来像函数定义,但没有参数列表;跳过表观身体
错误 C2988:无法识别的模板声明/定义

NestedClass作为

参数类型在范围内,因此您可以尝试以下操作:

 bool TemplateClass<T>::NestedClass::operator<(const NestedClass& rhs) const

MSVC可能在第一个版本上有问题。