gpt4 book ai didi

c++ - 如何声明模板化函数以便可以在类构造函数/函数中传递

转载 作者:太空狗 更新时间:2023-10-29 19:51:17 26 4
gpt4 key购买 nike

我想将用户定义的函数传递给需要用户定义的匹配函数的类。在过去的 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;
}

最佳答案

#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>
using match_key = bool (*)(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(const K& key, match_key<K> matchfunc) : key_(key), cmp(matchfunc) { }

bool matched(const K& key) {
return cmp(key_, key);
}

private:
const K key_;
match_key<K> 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;
}

关于c++ - 如何声明模板化函数以便可以在类构造函数/函数中传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49647846/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com