【问题标题】:How to pass a overloaded function pointer with a template data type?如何传递具有模板数据类型的重载函数指针?
【发布时间】:2020-05-25 17:04:55
【问题描述】:

在下面的代码中,我想创建一个函数count,它计算整数/字符串的数量,该数量符合向量的匹配条件整数/字符串.

但是我不清楚函数定义怎么写。

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

【问题讨论】:

  • bool (*test)(&lt;T&gt;) -> bool (*test)(T),还有(x.length &lt;= 3); -> (x.length() &lt;= 3);
  • 请在问题中包含错误

标签: c++ templates function-pointers stdvector function-templates


【解决方案1】:

函数指针类型为

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

意思是,您需要从count 函数中删除多余的&lt;&gt;,然后就可以开始了。

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)


附注

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多