为什么 std::less 是一个类模板

Why is std::less a class template?

本文关键字:一个 std less 为什么      更新时间:2023-10-16

根据 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,这些 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的decltypeauto关键字,这几乎是不必要的。

这就是

我们在 C++98 中的做法。现在我们更好地理解了模板和转发(拥有 14 年的经验),更新的函数类型可以按照您所说的去做:函数调用运算符是一个模板函数。

Stephan 提出的改变这一点的建议,以便所有此类函数对象在operator()中都是多态的,这是我的理解。

所以你的问题"为什么函数调用运算符没有模板化?"的答案就是这样。

相关文章: