STL 仿函数是这样实现的:
template<class T>
struct less{
bool operator()(T const& lhs, T const& rhs){
return lhs < rhs;
}
};
这让我们每次创建这样的仿函数时都会提到(可能是长的)类型。为什么它们没有像下面所示那样实现?有什么原因吗?
struct less{
template<class T>
bool operator()(T const& lhs, T const& rhs){
return lhs < rhs;
}
};
这将使它们无需提及(可能很长)类型即可使用。
最佳答案
这也使得将它们专门用于用户定义的类型是不可能的。
它们应该是一个自定义点。
总结评论中的讨论:
尽管按照 Xeo 的建议在技术上是可行的,但语言标准不允许这样做。
如果允许用户专门化模板的各个功能,则很难编写工作类模板。然而,在某些情况下,为用户定义的类型专门化整个类可能是个好主意。
因此 C++98 标准写道 (17.4.3.1):
It is undefined for a C++ program to add declarations or definitions to namespace std or namespaces within namespace std unless otherwise specified. A program may add template specializations for any standard library template to namespace std.
由于没有“另外指定” Xeo 的代码是允许的,我们理解它是不允许的。也许并不完全明显!或者说“模板特化”只适用于类。
新的 C++11 标准对这部分进行了扩展,并对其进行了更详细的说明(17.6.4.2):
The behavior of a C++ program is undefined if it adds declarations or definitions to namespace std or to a namespace within namespace std unless otherwise specified. A program may add a template specialization for any standard library template to namespace std only if the declaration depends on a user-defined type and the specialization meets the standard library requirements for the original template and is not explicitly prohibited.
The behavior of a C++ program is undefined if it declares
— an explicit specialization of any member function of a standard library class template, or
— an explicit specialization of any member function template of a standard library class or class template, or
— an explicit or partial specialization of any member class template of a standard library class or class template.A program may explicitly instantiate a template defined in the standard library only if the declaration depends on the name of a user-defined type and the instantiation meets the standard library requirements for the original template.
关于c++ - 为什么 STL 仿函数本身是模板化的,而不是它们的函数调用运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6575966/