我一直在研究 C++ 中的仿函数。特别是,我有一个 vector 对,我想按对的第一个元素排序。我开始编写一个完全专门化的仿函数(即类似“bool MyLessThan(MyPair &lhs, MyPair &rhs)”的东西)。然后,仅仅因为这类东西很有趣,我想尝试编写一个通用的“将 F 应用于这对的第一个元素”仿函数。我写了下面的内容,但 g++ 不喜欢它。我得到:
错误:“template struct Pair1stFunc2”的模板参数列表中参数 2 的类型/值不匹配 错误:需要一个类型,得到的是“less”
#include <algorithm>
#include <functional>
#include <utility>
#include <vector>
template <class P, class F>
struct Pair1stFunc2
{
typename F::result_type operator()(P &lhs, P &rhs) const
{ return F(lhs.first, rhs.first); }
typename F::result_type operator()(const P &lhs, const P &rhs) const
{ return F(lhs.first, rhs.first); }
};
typedef std::pair<int,int> MyPair;
typedef std::vector<MyPair> MyPairList;
MyPairList pairs;
void foo(void)
{
std::sort(pairs.begin(),
pairs.end(),
Pair1stFunc2<MyPair, std::less>());
}
任何人都可以阐明我在这里做错了什么吗?我知道这是一个稍微人为的例子,但我想知道发生了什么,如果只是为了提高我的 STL-fu。
最佳答案
为了扩展 dirkgently 的答案,这里有一个可能会如您所愿工作的示例:
template <typename T, template <typename> class F>
struct Pair1stFunc2
{
template <typename P>
typename F<T>::result_type operator()(P &lhs, P &rhs) const
{ F<T> f; return f(lhs.first, rhs.first); }
template <typename P>
typename F<T>::result_type operator()(const P &lhs, const P &rhs) const
{ F<T> f; return f(lhs.first, rhs.first); }
};
void foo(void)
{
std::sort(pairs.begin(),
pairs.end(),
Pair1stFunc2<int, std::less>());
}
请注意,它可以工作,但可能与您的想法不完全相同。
关于c++ - g++ 使用 "expected a type, got ' xyz' 拒绝我的简单仿函数”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/825015/