gpt4 book ai didi

C++ "greater"函数对象定义

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:35:57 26 4
gpt4 key购买 nike

template <class T> struct greater : binary_function <T, T, bool> {
bool operator() (const T& x, const T& y) const {
return x > y;
}
};

我在 STL 库中找到了“用于大于不等式比较的函数对象类”的定义。有人可以向我解释这段代码是如何工作和编译的吗?

最佳答案

template <class T> // A template class taking any type T
// This class inherit from std::binary_function
struct greater : binary_function <T, T, bool>
{
// This is a struct (not a class).
// It means members and inheritens is public by default

// This method defines operator() for this class
// you can do: greater<int> op; op(x,y);
bool operator() (const T& x, const T& y) const {
// method is const, this means you can use it
// with a const greater<T> object
return x > y; // use T::operator> const
// if it does not exist, produces a compilation error
}
};

这里是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;
};

这允许您访问定义 binary_function 的类型

greater<int> op;
greater<int>::result_type res = op(1,2);

相当于

std::result_of<greater<int>>::type res = op(1,2);

关于C++ "greater"函数对象定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12147566/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com