这是我为 std::map
容器和带有 Lambda 表达式的 std::vector
容器重载的两个函数。
有没有人看到一种方法来使它成为模板函数,它可以检查 Lambda 表达式的 pair
类型(在我的例子中是第二对)和常规范围类型(如 vector
、双端队列
等)。
bool isPlayerIn(vector<Player*> players, int id) {
vector<Player*>::iterator found = find_if(begin(players), end(players),
[id] (Player* player) {
return player->getId() == id;
});
return found != end(players);
}
bool isPlayerIn(map<int, Player*> players, int id) {
map<int, Player*>::iterator found = find_if(begin(players), end(players),
[id] (pair<int, Player*> found) {
return found.second->getId() == id;
});
return found != end(players);
}
最佳答案
这可以用一些 template metaprogramming 来解决,特别是类似 Boost's is_pair
的东西.这个想法是将微分从算法“下推”到仿函数。
请注意,对于您编写的类型的非常短的函数,您可能不会发现这是一个改进;对于更长的函数,涉及更复杂的算法,这将消除大量重复。
所以,您将有两个这样的类:
template<typename T, bool Pair>
matches_id :
std::unary_function<T, bool>
{
// Ctor taking id
// operator() deciding if t.second matches id
};
template<typename T>
matches_id<T, false> :
std::unary_function<T, bool>
{
// Ctor taking id
// operator() deciding if t itself matches id
};
在您的代码中,您将对类型的对象使用 find_if
matches_id<T, is_pair<T>::value>
关于c++ - 将一个函数的 vector + map 版本合并为一个兼容的版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34858435/