std::placeholders::_1, std::placeholders::_2, ..., std::placeholders::_N
来自cppreference.com
| 在标头 <functional> 定义
|
||
| |
||
std::placeholders 命名空间含有占位对象 [_1, . . . _N],其中 N 是实现定义的最大数字。
当用作 std::bind 表达式中的实参时,占位符对象被存储于生成的函数对象中,而以未绑定实参调用函数对象时,每个占位符 _N 被对应的第 N 个未绑定实参替换。
|
每个占位符如同以 |
(C++17 前) |
|
鼓励实现如同以 |
(C++17 起) |
占位符对象的类型可默认构造 (DefaultConstructible) 且可复制构造 (CopyConstructible) ,其默认复制/移动构造函数不抛异常,且对于任何占位符 _N,类型 std::is_placeholder<decltype(_N)> 有定义且从 std::integral_constant<int, N> 派生。
示例
下列代码展示以占位符实参创建函数对象。
Run this code
#include <functional>
#include <iostream>
#include <string>
void goodbye(const std::string& s)
{
std::cout << "Goodbye " << s << '\n';
}
class Object
{
public:
void hello(const std::string& s)
{
std::cout << "Hello " << s << '\n';
}
};
int main()
{
using namespace std::placeholders;
using ExampleFunction = std::function<void(const std::string&)>;
Object instance;
std::string str("World");
ExampleFunction f = std::bind(&Object::hello, &instance, _1);
f(str); // 等价于 instance.hello(str)
f = std::bind(&goodbye, std::placeholders::_1);
f(str); // 等价于 goodbye(str)
auto lambda = [](std::string pre, char o, int rep, std::string post)
{
std::cout << pre;
while (rep-- > 0)
std::cout << o;
std::cout << post << '\n';
};
// 绑定 lambda:
std::function<void(std::string, char, int, std::string)> g =
std::bind(&decltype(lambda)::operator(), &lambda, _1, _2, _3, _4);
g("G", 'o', 'o'-'g', "gol");
}
输出:
Hello World
Goodbye World
Goooooooogol
参阅
(C++11) |
绑定一或多个实参到函数对象 (函数模板) |
(C++11) |
指示对象是标准占位符,或者可以用作标准占位符 (类模板) |
(C++11) |
用 tie 解包 tuple 时用来跳过元素的占位符 (常量) |