fre*_*low 18 c++ templates stl operator-overloading generic-programming
根据20.8.5§1,std::less是一个具有成员函数的类模板:
template<typename T>
struct less
{
bool operator()(const T& x, const T& y) const;
// ...
};
Run Code Online (Sandbox Code Playgroud)
这意味着我必须在实例化模板时提及类型std::less<int>.为什么不是std::less具有成员函数模板的普通类呢?
struct less
{
template<typename T, typename U>
bool operator()(const T& x, const U& y) const;
// ...
};
Run Code Online (Sandbox Code Playgroud)
然后我可以简单地传递std::less给没有类型参数的算法,这可能会变得毛茸茸.
这只是出于历史原因,因为早期的编译器(据说)不能很好地支持成员函数模板(或者甚至根本不支持),或者有更深刻的东西吗?
Cha*_*via 27
这样实例化模板创建的类具有嵌套的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;
};
Run Code Online (Sandbox Code Playgroud)
std::less继承自std::binary_function生成这些typedef的.例如,您可以使用提取结果类型std::less<T>::result_type.
如今,对于C++ 11 decltype和auto关键字来说,这几乎是不必要的.
| 归档时间: |
|
| 查看次数: |
5665 次 |
| 最近记录: |