为类定义之外的模板类定义运算符[]()(数组订阅)

Define operator[]() (array subscription) for template class outside of class definition

本文关键字:定义 数组 运算符      更新时间:2023-10-16

我以为这很容易,但它并没有按照我预期的方式工作。 这里的正确语法是什么?

模板类.h

template <typename T> 
class TemplateClass
{
  T & operator[](size_t n);

模板类.cpp

#include "TemplateClass.h"
template <typename T>
T & TemplateClass::operator[](size_t n)
{
  // member declaration not found
}

您需要提供整个类名 - 包括模板参数:

template <typename T>
T & TemplateClass<T>::operator[](size_t n)
{
  // ...
}

(另请注意,范围解析运算符是 :: ,而不是 :