尝试从模板化函数返回向量会引发编译错误
Trying to return a vector from a templated function throws compiling errors.
>问题如下:以下测试抛出大量编译器错误。
#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++模板类中,模板成员函数必须在类内部定义其主体,因为模板参数在类外部不存在。最后两个错误看起来像编译器在不熟悉的上下文导致它误解完全有效的语法时产生的结果。尝试在类内移动函数体。
相关文章:
- C++中函数的向量返回类型引发错误
- 尝试将unique_ptrs推送到向量时使用纯虚拟函数错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 如何使用C++初始化向量;脚本化值不是数组、指针或矢量错误
- 对象指针 c++ 的全局向量错误
- C++:自定义数据类型向量错误的队列
- getCompatibleComponent返回向量错误
- FlatBuffers:未支撑的工会向量错误将JSON文件转换为二进制文件
- 尝试调用 at() 时 c++ 中的向量错误
- 结果向量错误
- 尝试用函数填充线程向量 - 错误
- C++ 布尔向量错误:赋值时"iterator not dereferencable"
- CUDA 推力:类的:d向量 |错误
- C++多结构向量错误
- c++正则化向量;错误:无法绑定
- c++向量错误
- 向量错误抛掷分配经验甚至不访问任何元素
- std::函数的向量错误
- STL向量错误:未知类型名称
- 向量错误分配错误 C++