首页 > 解决方案 > 怎么修错误:无法从“初始化列表”转换为 asdendingCompare(模板函子)

问题描述

我正在尝试使用模板仿函数(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]);*/
}

使用仿函数的部分

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 错误:无法从“初始化列表”转换为“升序比较”

标签: c++visual-studiocompiler-errors

解决方案


如上回答

在尝试触发 operator() 之前,您从未创建过ascendingCompare 的实例。您的 asrendingCompare( arr[j + 1], arr[j]) 试图从这些参数中构造,这显然是错误的。

所以正确的形式是

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]) )

推荐阅读