Ned*_*Ned 5 c++ templates g++ functor
我一直在玩C++中的仿函数.特别是,我有一个对的向量,我想根据该对的第一个元素排序.我开始编写一个完全专业的函子(例如"bool MyLessThan(MyPair&lhs,MyPair&rhs)").然后,仅仅因为这种东西很有趣,我想尝试编写一个通用的"将F应用于这对的第一个元素"仿函数.我写了下面的内容,但是g ++并不喜欢它.我明白了:
错误:模板参数列表中参数2的类型/值不匹配'template struct Pair1stFunc2'错误:预期类型,得到"更少"
#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>());
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以解释我在这里做错了什么吗?我知道这是一个有点人为的例子,但我想知道发生了什么,如果只是为了改善我的STL-fu.
小智 6
为了扩展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>());
}
Run Code Online (Sandbox Code Playgroud)
请注意它有效,但它可能不是您想到的.
您需要使用您正在使用的比较类型来专门化 std::less 。
Pair1stFunc2<MyPair, std::less<int> >()
Run Code Online (Sandbox Code Playgroud)
会成功的。在您自己的operator()中,您还需要实例化比较类型的对象,因为您不能直接调用该类。例如改变
return F(lhs.first, rhs.first);
Run Code Online (Sandbox Code Playgroud)
到
F func;
return func(lhs.first, rhs.first);
Run Code Online (Sandbox Code Playgroud)
正如另一个答案所建议的那样,您还可以将专业化转移到函子中。
| 归档时间: |
|
| 查看次数: |
3333 次 |
| 最近记录: |