模板的问题
Template problems
本文关键字:问题 更新时间:2023-10-16
我有这个简单的排序程序,它应该适用于Set<int>
-s的向量,它适用于基本类型,我使用其他一些比较函数非基本类型,它工作得很好,但一旦我尝试比较集合它崩溃了错误:
error C2782: 'void Sort(Vector<ElemType> &,int (__cdecl *)(type,type))' : template parameter 'type' is ambiguous
我该如何解决这个问题?
template <typename type>
void swap(int &a, int &b){
type tmp =a;
a = b;
b = tmp;
}
template <typename type>
void Sort(Vector<type>& vec,int (cmp) (type,type) = OperatorCmp ){
while(true){
for(int i =1; i < v.size(); i++){
if(cmp(v[i-1],v[i]) > 0){
break;
}else{
return;
}
}
int index1 = RandomInteger(0,vec.size()-1);
int index2 = RandomInteger(0,vec.size()-1);
swap(vec[index1],vec[index2]);
}
}
int main(){
Randomize();
Vector<char>a;
Sort(a);
return 0;
}
类型不匹配。bozoSort
声明为:
template <typename T>
void bozoSort(Vector<T>& vec, int (cmp) (T,T) );
当你用a
调用它时,你希望推导出T = Set<int> >
,这将是签名:
void bozoSort(Vector<Set<int> >& vec, int (cmp) (Set<int>, Set<int> ));
但是,您使用compareSets
调用它,其签名为int (Set<int>&, Set<int>&)
。它们不匹配,所以编译器不能为你解析模板。更好的解决方案是将整个比较器作为模板:
template <typename T, typename Compare>
void bozoSort(Vector<T>& vec, Compare cmp) { ... }
这样,如果您希望比较器通过引用、const引用或value获取参数,那么上述任何一种方法都可以很好地工作。
type
推导为对函数指针形参Set<int>
的引用,对容器值类型Set<int>
的引用,这是一个不一致的推导。最简单的解决方案:完全泛化函子:
template <typename type, typename Fun>
bool isSorted(Vector<type> & vec, Fun cmp){
for(int i =0; i < vec.size()-1; i++){
if(cmp(vec[i],vec[i+1]) > 0)return false;
}
return true;
}
. .
你有
template <typename type>
void bozoSort(Vector<type>& vec,int (cmp) (type,type) = OperatorCmp )
用
调用vec = Vector<Set<int>>
和
cmp = compareSets
int compareSets(Set<int>& a , Set<int>& b){
现在对于vec
, type
只能是Set<int>
,而对于cmp
, type
只能是Set<int>&
。
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 基于boost的程序的静态链接——zlib问题
- C++格式化输出问题
- 使用mongocxx驱动程序时包含头文件问题