gpt4 book ai didi

c++ - 尝试从模板化函数返回 vector 会引发编译错误。

转载 作者:太空宇宙 更新时间:2023-11-04 12:04:41 25 4
gpt4 key购买 nike

问题如下:下面的测试会抛出大量的编译器错误。

#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,您告诉编译器将声明解析为类型。

请阅读Where and why do I have to put the “template” and “typename” keywords?以获得深入的解释。

关于c++ - 尝试从模板化函数返回 vector 会引发编译错误。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12683495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com