函数模板中出现奇怪错误

Strange error in function templates

本文关键字:错误 函数模板      更新时间:2023-10-16

我正在学习C++中的函数模板,所以我写了一个简单的函数来消除重复。但编译器抛出以下错误。

removeDup is not a function or static data member

using namespace std;  
template <typename T>  
void removeDup(std::vector<T>& vec)  
{  
std::sort(vec.begin(), vec.end());  
vec.erase(std::unique(vec.begin(), vec.end()), vec.end());  
}  

可能是什么问题?

编译器的错误通常是相关的。例如,如果您不匹配块大括号,可能会导致许多不在范围内的标识符。通常情况下,第一个是根本原因,人们很容易忽视其他原因。在这种情况下,后面的错误才是重要的,而第一个则远非显而易见。

未能包含堆栈使removeDup让编译器感到困惑,它首先抱怨removeDup。

添加后代码编译得很好:

#include <vector>
#include <algorithm>

using namespace std;之前

如果没有这些内容,这就是我从gcc 4.2(愚蠢的Mac)得到的错误:

template.cpp:6: error: variable or field ‘removeDup’ declared void
template.cpp:6: error: ‘vector’ is not a member of ‘std’
template.cpp:6: error: expected primary-expression before ‘>’ token
template.cpp:6: error: ‘vec’ was not declared in this scope

第一行与非常接近

removeDup is not a function or static data member

这对我来说很好:

#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;  
template <typename T>  
void removeDup(std::vector<T>& vec)  
{  
std::sort(vec.begin(), vec.end());  
vec.erase(std::unique(vec.begin(), vec.end()), vec.end());  
}  
int main()
{
int values[] = {1,2,3,3,3};
vector<int> ints(values, values + 5);
removeDup(ints);
for (vector<int>::iterator it=ints.begin(); it!=ints.end(); ++it)
cout << " " << *it;
return 0;
}
$ g++ c.cpp
$ ./a.out
1 2 3