2012-12-13 39 views
17

根据20.8.5§1,std::less是类模板与一个成员函数:为什么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到不带类型参数的算法,这可能会很麻烦。

这仅仅是出于历史原因,因为早期的编译器(据推测)不能很好地支持成员函数模板(或者甚至可能),还是有更深刻的东西呢?

+1

'std :: string a; std :: less()(a,“HI”);'(参见'std :: lower_bound') –

+7

C++ 14将包含一个特殊化,以使std :: less <>()完全转发。参见[N3421](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3421.htm),我认为这是我在波特兰未经修改而采用的。 –

+0

@MooingDuck'std :: less()(a,“HI”)'在我的系统上是'true',这是一个问题吗? – fredoverflow

回答

27

这使得由实例化的模板创建的类具有嵌套的typedef,其提供关于结果类型和参数类型的仿函数的类型的信息:从std::binary_function

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::less<T>::result_type提取结果类型。

如今,这对于C++ 11的decltypeauto关键字来说基本没有必要。

+3

+1很好的答案。 – Mehrdad

9

这就是我们在C++ 98中完成它的方式。现在我们已经理解了模板和转发的更好(拥有14年以上的经验),更新的函数类型可以完成您所说的内容:函数调用操作符是一个模板函数。

1

斯蒂芬提出的改变这种方式,使所有这些函数对象在它们的operator()中是多态的被上次会议接受,这是我的理解。

因此,您的问题“为什么函数调用操作符不是模板?”的答案就是这样。

相关问题