![](/img/trans.png)
[英]How to pass a member function pointer to an overloaded method in a template function?
[英]How to pass a overloaded function pointer with a template data type?
在下面的代码中,我想创建一个 function count
,该计数从整数/字符串向量中计算符合匹配标准的整数/字符串的数量。
但是我不清楚如何编写 function 定义。
#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>) )
function 指针类型为
<return-type>(*function-pointer-identifier)(<argument-types>)<other specifiers>
意思是,您需要从count
function 中删除额外的<>
,并且您对 go 很好。
template <typename T>
int count(std::vector<T>& V, bool (*test)(T))
// ^^^^^^^^^^^^^^^^^
或者,您可以为 function 指针类型提供模板类型别名,这可能更易于阅读
template <typename T>
using FunPtrType = bool (*)(T); // template alias
template <typename T>
int count(std::vector<T>& V, FunPtrType<T> test)
{
// ...
}
(见演示)
旁注
std::string::length
function 时有错字。 bool match(std::string x) { return x.length() <= 3; // missing () here }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.