我正在尝试使用模板函数器(ascendingCompare)来比较两个值,并在排序数组的模板函数( sort )中使用它
函数式
template<typename Q>
class ascendingCompare
{
public:
bool operator () (const Q &first, const Q &second)
{
if (first < second)
return true;
else
return false;
}
};
排序函数和用于交换值的函数
template <typename Q>
void Swap(Q &first, Q &second)
{
Q temp = first;
first = second;
second = temp;
}
template <typename W>
void sortAscend(W *arr, int size)
{
for (int i = 0; i < size - 1; i++)
for (int j = 0; j < size - 1 - i; j++)
if (ascendingCompare<W>( arr[j + 1], arr[j]) )
Swap(arr[j + 1], arr[j]);
/*if (arr[j + 1] < arr[j])
Swap(arr[j + 1], arr[j]);*/
}
使用functor的部分
int *sorted_array = new int[array_size];
for (int counter = 0; counter < array_size; counter++)
{
sorted_array[counter] = rand() % 100;
cout << setw(2) << sorted_array[counter] << " ";
}
sortAscend(sorted_array, array_size);
所以编译器给出这个列表错误:不能从‘C2440’转换为"ascendingCompare“
发布于 2019-03-31 19:19:18
如上所述
在尝试触发operator()之前,您从未创建过ascendingCompare的实例。您的ascendingCompare( arrj + 1,arrj)试图从这些参数构造,这显然是错误的。
所以正确的形式应该是
template <typename W>
void sortAscend(W *arr, int size)
{
for (int i = 0; i < size - 1; i++)
for (int j = 0; j < size - 1 - i; j++)
if (ascendingCompare<W>()( arr[j + 1], arr[j]) )
Swap(arr[j + 1], arr[j]);
/*if (arr[j + 1] < arr[j])
Swap(arr[j + 1], arr[j]);*/
}
因此,如果您对实际发生了什么变化感到困惑
旧版本
if (ascendingCompare<W>( arr[j + 1], arr[j]) )
新版本
if (ascendingCompare<W>()( arr[j + 1], arr[j]) )
https://stackoverflow.com/questions/55444299
复制相似问题