如何传递带有模板数据类型的重载函数指针?

问题描述 投票:0回答:1

在下面的代码中,我想创建一个函数count,该函数对integers / strings的数量进行计数,该数量可以从integers / strings的向量中限定匹配条件。但我不清楚如何编写函数定义。

#include <iostream>
#include <vector>
using namespace std;

bool match (int x) {
    return (x%2 == 0);
}
bool match (string x) {
    return (x.length <= 3);
}
template <typename T>
int count (vector<T> &V , bool (*test)(<T>) ) {
    int tally =0;
    for (int i =0; i <V.size() ; i++) {
        if (test(V[i])) {
            tally++;
        }
    }
    return tally;
}
int main() {
    vector <int> nums;
    vector <string> counts;
    nums.push_back(2);
    nums.push_back(4);
    nums.push_back(3);
    nums.push_back(5);
    counts.push_back("one");
    counts.push_back("two");
    counts.push_back("three");
    counts.push_back("four");
    cout << count(nums , match) << endl;
    cout << count (counts , match) << endl;
}

原型应如何编写?我意识到错误就在这行

int count (vector<T> &V , bool (*test)(<T>) ) 
c++ templates vector function-pointers
1个回答
0
投票

功能指针类型为

<return-type>(*function-pointer-identifier)(<argument-types>)<other specifiers>

意思是,您需要从<>功能中删除多余的count,并且一切顺利。

template <typename T>
int count(std::vector<T>& V, bool (*test)(T))
//                           ^^^^^^^^^^^^^^^^^

或者您可以为函数指针类型提供模板类型别名,这可能使阅读更容易

template <typename T>
using FunPtrType = bool (*)(T); // template alias

template <typename T>
int count(std::vector<T>& V, FunPtrType<T> test)
{
   // ...
}

([See a demo


此外,在调用std::string::length函数时遇到错字。

bool match(std::string x)
{
   return x.length() <= 3; // missing () here
}

也请看[Why is "using namespace std;" considered bad practice?

© www.soinside.com 2019 - 2024. All rights reserved.