【发布时间】:2018-04-04 09:46:55
【问题描述】:
我想将用户定义的函数传递给需要用户定义的匹配函数的类。在过去的 C 语言时代,我会使用带有 void* 参数的函数指针。但一定有更好的办法……
这大概是我想做的事情。我的一个限制是我所在的平台没有标准库。但是基本的核心语言C++11是可用的。
我需要做什么:
#include <iostream>
using namespace std;
// TODO - replace this C construct with C++ equivalent
//typedef bool(*match_key)(const void* key1, const void* key2);
// somehow declare this as a typedef? need a way to declare a signature in C++
typedef template<class T>
bool (*match_key)(const T& key1, const T& key2);
// *** User defined matching function
bool mymatcher(const int i, const int j) {
return i == j;
}
template<class K>
class hashmap {
public:
hashmap<K>(const K& key, match_key matchfunc) : key_(key), cmp(matchfunc) { }
bool matched(const K& key) {
return cmp(key_, key);
}
private:
const K key_;
match_key cmp;
};
int main()
{
int i = 3;
int j = 4;
hashmap<int> hm(i, mymatcher);
cout << "i matches j? " << (hm.matched(j) ? "yes" : "no") << endl;
return 0;
}
【问题讨论】:
-
你错过了
template <class K>和public:之间的class hashmap {吗? -
@user463035818 - 只是检查你是否注意了:)
标签: c++ function-pointers function-prototypes