根据 20.8.5 §1,std::less
是一个带有成员函数的类模板:
template<typename T>
struct less
{
bool operator()(const T& x, const T& y) const;
// ...
};
这意味着我在实例化模板时必须提及类型,例如 std::less<int>
.为什么不是 std::less
一个带有成员函数模板的普通类?
struct less
{
template<typename T, typename U>
bool operator()(const T& x, const U& y) const;
// ...
};
那么我可以简单地通过 std::less
到没有类型参数的算法,这可能会变得很麻烦。
这只是出于历史原因,因为早期的编译器(据说)不能很好地支持成员函数模板(甚至可能根本不支持),还是有更深刻的原因?
最佳答案
因此,由实例化模板创建的类具有嵌套的 typedef,它们提供有关仿函数的结果类型和参数类型的类型信息:
template <class Arg1, class Arg2, class Result>
struct binary_function
{
typedef Arg1 first_argument_type;
typedef Arg2 second_argument_type;
typedef Result result_type;
};
template <class T>
struct less : binary_function <T,T,bool>
{
bool operator() (const T& x, const T& y) const;
};
std::less
继承自 std::binary_function
,它产生这些类型定义。例如,您可以使用 std::less<T>::result_type
提取结果类型。 .
如今,对于 C++11 的 decltype
,这几乎是不必要的。和 auto
关键字。
关于c++ - 为什么 std::less 是类模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13867996/