函数模板中出现奇怪错误
Strange error in function templates
我正在学习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
相关文章:
- 使用具有默认参数的函数模板进行 decltype 会使结果混乱(一个有趣的问题或 gcc 的错误)
- C++ 将派生类的成员函数指针作为参数传递时选择了错误的模板专用化
- 函数模板不起作用,出现错误"No suitable user-defined conversion"
- 在编写包装现有函数并检查错误的模板函数时,如何使用完美转发?
- 函数模板(它是类模板的成员)的显式专用化会产生"partial specialization is not allowed"错误,为什么?
- 错误:重新定义函数模板(或 C2995)
- 错误 C2893 无法专门化函数模板'unknown-type std::invoke(_Callable &&,_Types &&...)'
- 函数模板专用化生成链接错误
- CUDA 模板错误:没有与参数列表匹配的函数模板实例
- 函数模板中的无效转换错误,返回值取决于其泛型类型
- 常量正确性编译错误到模板函数中的无效转换错误
- (C++)(链接错误)模板成员函数上未解析的外部
- 精神语法不会编译:函数模板参数错误?
- 包含格式错误的模板成员函数的格式正确的程序?
- 带有返回类型的错误调用模板到会员函数
- 调用了错误的模板函数
- 错误 C2893:无法使用 CTPL 专用化函数模板
- 为什么从 void 函数模板返回时没有收到编译器错误?
- C 错误:呼叫函数模板没有匹配功能
- 实例化错误后成员函数模板的专业化,以及成员函数的顺序