尝试从模板化函数返回向量会引发编译错误

Trying to return a vector from a templated function throws compiling errors.

本文关键字:向量 错误 编译 返回 函数      更新时间:2023-10-16

>问题如下:以下测试抛出大量编译器错误。

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

一些编译器错误:

 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'

但是,如果您换掉模板化vector<T>vector<float>它的编译就可以了。例如:

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

关于为什么的任何想法?

您需要

在两个位置添加typename

typename vector<T>::iterator begin();

typename vector<T>::iterator test<T>::begin()

通过添加typename,您告诉编译器如何解析代码。基本上,通过添加 typename ,您告诉编译器将声明解析为类型。

请阅读我必须

在哪里以及为什么必须放置"模板"和"类型名称"关键字?以获得深入的解释。

您需要

使用 typename 关键字来区分vector<T>::iterator引用的作用域类型,而不是作用域内数据或函数成员:

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

在C++模板类中,模板成员函数必须在类内部定义其主体,因为模板参数在类外部不存在。最后两个错误看起来像编译器在不熟悉的上下文导致它误解完全有效的语法时产生的结果。尝试在类内移动函数体。