比如
template<typename T>
struct Greater
{
bool operator () (const T& lhs, const T& rhs)
{
return lhs > rhs;
}
};
struct Less
{
template<typename T>
bool operator () (const T& lhs, const T& rhs)
{
return lhs < rhs;
}
};
单就使用而言, 上面的Less肯定更方便, 比如语法
sort(vec.begin(), vec.end(), Greater<int>());
sort(vec.begin(), vec.end(), Less());
包括在其他算法模板当中, 使用Less的话, 可能有时候可以绕过traits实现某些功能
但其实STL等库充斥着类模板, 即使当时使用函数模板也能实现功能
我勉强想一下:
当对上面Greater和Less多次调用的时候, Greater一直都是用户直接指定的类型, 所以都能立刻定位到()运算符, 而Less在多次
模板实例化后会有多个函数重载, 匹配正确的函数签名还是比Greater慢了, 两种实现方法, 是在编译期存在速度上的差异?
struct Less
{
template<typename T>
bool operator () (const T& lhs, const T& rhs)
{
return lhs < rhs;
}
};
template<typename FT, typename T>
class FirstBinder
{
public:
FirstBinder(FT fn, const T& p1st):
m_fn(fn),
m_p1st(p1st)
{
}
// template<typename SecondT>
bool operator () (const T& p2nd)
{
return m_fn(m_p1st, p2nd);
}
private:
FT m_fn;
const T& m_p1st;
};
template<typename FT, typename FirstT>
inline FirstBinder<FT, FirstT> bindFirst(FT fn, const FirstT& p1st)
{
return FirstBinder<FT, FirstT>(fn, p1st);
};