任何定义了函数调用操作符的对象都是函数对象。C++ 支持创建、操作新的函数对象,同时也提供了许多内置的函数对象。
部分函数应用
std::bind_front 与 std::bind 提供部分函数应用的支持,即绑定参数到函数以创建新函数。
指示对象为 std::bind 表达式,或能被用作这种表达式
std::is_bind_expression
|
template< class T > |
(C++11 起) |
若
此模板可对用户定义类型
帮助变量模板
|
template< class T > |
(C++17 起) |
继承自 std::integral_constant
成员常量
|
value [静态] |
若 (公开静态成员常量) |
成员函数
|
operator bool |
转换对象为 bool ,返回 (公开成员函数) |
|
operator() (C++14) |
返回 (公开成员函数) |
成员类型
| 类型 | 定义 |
| std::integral_constant<bool, value> |
调用示例
#include <iostream>
#include <type_traits>
#include <functional>
struct Cell
{
int x;
int y;
Cell() = default;
Cell(int a, int b): x(a), y(b) {}
Cell(const Cell &cell)
{
x = cell.x;
y = cell.y;
}
bool operator <(const Cell &cell) const
{
if (x == cell.x)
{
return y < cell.y;
}
else
{
return x < cell.x;
}
}
Cell &operator+(const Cell &cell)
{
x += cell.x;
y += cell.y;
return *this;
}
};
std::ostream &operator<<(std::ostream &os, const Cell &cell)
{
os << "{" << cell.x << "," << cell.y << "}";
return os;
}
struct MyBind
{
typedef Cell result_type;
Cell operator()(Cell cell1, Cell cell2) const
{
return cell1 + cell2;
}
};
namespace std
{
template<>
struct is_bind_expression<MyBind> : public true_type {};
}
Cell Function1(Cell cell1, Cell cell2)
{
return cell1 + cell2;
}
int main()
{
std::cout << std::boolalpha;
// 如同 bind(Function1, bind(MyBind::operator(), _1, _2), Cell{108, 108})
auto function1 = std::bind(Function1, MyBind(), Cell{108, 108});
std::cout << "Adding Cell{108, 108} to the sum of Cell{106, 106} and Cell{107, 107} gives "
<< function1(Cell{106, 106}, Cell{107, 107}) << std::endl;
std::cout << "std::is_bind_expression<MyBind>::value: "
<< std::is_bind_expression<MyBind>::value << std::endl;
return 0;
}
输出
Adding Cell{108, 108} to the sum of Cell{106, 106} and Cell{107, 107} gives {321,321}
std::is_bind_expression<MyBind>::value: true