为什么 std::less 是一个类模板
Why is std::less a class template?
根据 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的decltype
和auto
关键字,这几乎是不必要的。
这就是
我们在 C++98 中的做法。现在我们更好地理解了模板和转发(拥有 14 年的经验),更新的函数类型可以按照您所说的去做:函数调用运算符是一个模板函数。
Stephan 提出的改变这一点的建议,以便所有此类函数对象在operator()
中都是多态的,这是我的理解。
所以你的问题"为什么函数调用运算符没有模板化?"的答案就是这样。
相关文章:
- 库函数需要一个 std::function<void(void)>,如何传入类函数?
- 将 std::array 移动到另一个 std::array
- 为什么 Clang std::ostream 写一个 std::istream 无法读取的双精度?
- 访问 std:vector 的类成员 std:vector 在一个类中与另一个 std:vector
- 是否有一个 std::set 函数来确定不超过数字 x 的最大元素?
- 除了 std::vector 之外,是否有一个 std 容器不会复制和销毁作为类的元素?
- 我正在将一个 std::string 传递给一个 boost 函数,该函数对该类型进行常量引用,但该值发生了变化
- 在线程 A 中创建一个 std::thread 对象,在线程 B 中连接
- 使用 glDrawElements 绘制一个 std::vector
- 从 C 字符串构造 std::string 与从另一个 std::string 构造 std::string 不一致
- 我可以得到一个字符 * 到一个 std::sregex_iterator 匹配 str() 吗?
- 如何有效地将(一些)项目从一个std::map移动到另一个std::map
- 我可以制作一个std::set的constexpr对象吗
- 打印一个带有静态 int 的函数,有一个 std::cout 和多个 std::cout 有什么区别?
- Visual Studio 2017 STL 可视化工具失败了一个 std::map<MyIntrusivePtr, std::tuple<....> >
- 如何设置一个 std::vector 与另一个,其中两个是不同类的向量?
- SWIG:传递一个 std::vector< std::vector <double> >指向 python 的指针
- 如何构造一个 std::variant 类型对象,其自身 Templated 和构造函数转发参数
- 如何声明一个 std::用不同值内联初始化的结构数组
- 将对象从一个 std::d eque 移动到另一个的更好方法