【问题标题】:Receiving error C2664: cannot convert parameter 1 from 'std::vector<_Ty>' to 'std::vector<_Ty,_Ax> &' when passing vector<int> to templated method接收错误 C2664:无法将参数 1 从 'std::vector<_Ty>' 转换为 'std::vector<_Ty,_Ax> &' 将 vector<int> 传递给模板化方法时
【发布时间】:2012-07-22 19:20:54
【问题描述】:

我在我的 cpp 函数中引用了一个模板化的快速排序方法,如下所示:

Main.cpp

QuickSort<vector<int>>(testData);

testData 在哪里:

int arr[] = {0, 5, 3, 4, 2, 1, 4};
vector<int> testData (arr, arr + sizeof(arr) / sizeof(arr[0]));

.h文件中quicksort的声明为:

排序.h

template <typename T>
void QuickSort(std::vector<T>& Unsorted);

而函数定义为:

排序.cpp

template <typename T>
void QuickSort(std::vector<T>& Unsorted) 
{
         //implementation here
}

我是不是疯了?我只是想通过引用传递一个整数向量。谁能告诉我哪里出错了?

【问题讨论】:

  • 可能是因为QuickSort&lt;vector&lt;int&gt;&gt; 中的移位运算符?这是 C++0x 之前的任何问题,请参阅 here
  • @Joost 将 impl 移到一个位置后会出现该问题,但大多数现代编译器已经区分了位移模板和嵌套模板

标签: c++ templates


【解决方案1】:

模板不能有单独的定义和声明

还有

QuickSort<int>(vec);

如果函数声明和定义必须在saem地方,即:

#include <vector>

template <typename T>
void qs(std::vector<T>&v );

int main() {
  std::vector<int> v;
  qs(v);
}


void qs(std::vector<T>&v ) { 
}

不会编译,当

#include <vector>

template <typename T>
void qs(std::vector<T>&v ) {}

int main() {
  std::vector<int> v;
  qs(v);
}

编译得很好,在 stl 中检查模板函数是如何制作的。 问题是,编译器在使用它之前必须知道整个函数,而在你的情况下他不知道

【讨论】:

  • 这是一条不同的错误消息。这里是编译器报告,而不是链接器。
  • -1:是的,他们可以。定义一般不能放在 .cpp 文件中,但它们可以分开
  • 作者不认为 def 在 hpp 中,还要检查编辑,以确保正确调用
  • 谢谢 - 调用函数错误。哦。我讨厌这样的错误。
  • 还有——Bartek,你为什么不能把模板化函数的定义放到cpp文件中?将它们保存在头文件中似乎很愚蠢?
猜你喜欢
  • 1970-01-01
  • 2011-04-14
  • 1970-01-01
  • 2017-06-19
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多