为什么std :: less是一个类模板? [英] Why is std::less a class template?

查看:255
本文介绍了为什么std :: less是一个类模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据20.8.5§1, std :: less 是具有成员函数的类模板:

According to 20.8.5 §1, std::less is a class template with a member function:

template<typename T>
struct less
{
    bool operator()(const T& x, const T& y) const;
    // ...
};

这意味着我在实例化模板时必须提到类型,例如 std :: less< int> 。为什么 std :: less 是成员函数模板的普通类?

Which means I have to mention the type when I instantiate the template, for example std::less<int>. Why isn't std::less a normal class with a member function template instead?

struct less
{
    template<typename T, typename U>
    bool operator()(const T& x, const U& y) const;
    // ...
};

然后我可以简单地传递 std :: less

Then I could simply pass std::less to an algorithm without the type argument, which can get hairy.

这是因为历史原因,因为早期的编译器(据说)不支持成员函数模板非常好(或者甚至可以),还是有更深刻的东西?

Is this just for historic reasons, because early compilers (supposedly) did not support member function templates very well (or maybe even at all), or is there something more profound to it?

推荐答案

实例化模板具有嵌套的typedef,其提供关于函子的结果类型和参数类型的类型信息:

It's so that the class created by the instantiated template has nested typedefs which provide type information about the result type and argument types of the functor:

  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 ,它产生这些typedef。例如,您可以使用 std :: less< T> :: result_type 提取结果类型。

std::less inherits from std::binary_function, which produces these typedefs. So for example, you can extract the result type using std::less<T>::result_type.

现在,这对于C ++ 11的 decltype auto 关键字是不必要的。

Nowadays, this is mostly unnecessary with C++11's decltype and auto keywords.

这篇关于为什么std :: less是一个类模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆