1

这些是我的两个重载函数,用于std::map容器和std::vector具有 Lambda 表达式的容器。

有没有人看到一种使它成为模板函数的方法,它可以检查 Lambda 表达式的pair类型(在我的情况下是对的第二个)和常规范围类型(​​如vector,deque等)。

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);
}
4

1 回答 1

1

This can be solved with some template metaprogramming, specifically something like Boost's is_pair. The idea is to "push down" the differentiation from the algorithm to the functor.

Note that for a very short function of the type you wrote, you might not find this an improvement; for longer functions, involving more complex algorithms, this would remove a lot of the duplication.

so, you'd have two classes like so:

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
};

In your code, you'd use find_if with an object of type

matches_id<T, is_pair<T>::value>
于 2016-01-18T15:55:56.433 回答