如何将函数指针指向以模板作为参数的函数? 我正在尝试指向这个函数
template<typename BaseType>
int indexOfLargest(const BaseType list[], int startIndex, int endIndex) {
if (startIndex < 0 || startIndex > endIndex)
return -1;
int indexOfMax = startIndex;
for (int index = startIndex + 1; index < endIndex; index++)
if (list[index] > list[indexOfMax])
indexOfMax = index;
return indexOfMax;
}
还有这个函数
template<typename BaseType>
int indexOfSmallest(const BaseType list[], int startIndex, int endIndex) {
if (startIndex < 0 || startIndex > endIndex)
return -1;
int indexOfMin = startIndex;
for (int index = startIndex + 1; index < endIndex; index++)
if (list[index] < list[indexOfMin])
indexOfMin = index;
return indexOfMin;
}
这样我就可以避免在每次迭代时都执行 if 语句。
template<typename A0, typename A1, typename A2, typename A3, typename A4>
void sortArrayData(A0 a0[], A1 a1[], A2 a2[], A3 a3[], A4 a4[],
const int recordCount, int order) {
int indexOfNext;
for (int index = 0; index < recordCount - 1; index++) {
if (order == 1)
indexOfNext = indexOfSmallest(a0, index, recordCount);
else
indexOfNext = indexOfLargest(a0, index, recordCount);
swap_v(a0[index], a0[indexOfNext]);
swap_v(a1[index], a1[indexOfNext]);
swap_v(a2[index], a2[indexOfNext]);
swap_v(a3[index], a3[indexOfNext]);
swap_v(a4[index], a4[indexOfNext]);
}
}
-- additional I could not find any answers for this online or from fellow programmers.
谢谢
最佳答案
有几种方法。您可以让编译器为您解决:
template<typename A0, typename A1, typename A2, typename A3, typename A4, typename F>
void sortArrayData(A0 a0[],
A1 a1[],
A2 a2[],
A3 a3[],
A4 a4[],
const int recordCount,
F indexFunc)
{
int indexOfNext;
for (int index = 0; index < recordCount - 1; index++) {
indexOfNext = indexFunc(a0, index, recordCount);
// ...
}
}
或者您可以直接将签名指定为函数或 std::function。
template<typename A0, typename A1, typename A2, typename A3, typename A4>
void sortArrayData(A0 a0[],
A1 a1[],
A2 a2[],
A3 a3[],
A4 a4[],
const int recordCount,
std::function<int (A0, int, int)> indexFunc)
{
int indexOfNext;
for (int index = 0; index < recordCount - 1; index++) {
indexOfNext = indexFunc(a0, index, recordCount);
// ...
}
}
你也可以为函数声明一个局部变量:
template<typename A0, typename A1, typename A2, typename A3, typename A4>
void sortArrayData(A0 a0[],
A1 a1[],
A2 a2[],
A3 a3[],
A4 a4[],
const int recordCount,
int order)
{
std::function<int (A0, int, int)> indexFunc = (order == 1) ? (indexOfSmallest) : (indexOfSmallest);
int indexOfNext;
for (int index = 0; index < recordCount - 1; index++) {
indexOfNext = indexFunc(a0, index, recordCount);
// ...
}
}
关于指向以模板作为参数的函数的 C++ 函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23070646/