std::placeholders::_1, std::placeholders::_2, ..., std::placeholders::_N
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
旧绑定器与适配器 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
在标头
<functional>
定义
|
||
/*see
below*/ _1;
/*see below*/ _2; |
||
std::placeholders 命名空间含有占位对象
[_1, . . . _N]
,其中 N
是实现定义的最大数字。
于 std::bind
表达式用作参数时,占位符对象被存储于生成的函数对象,而以未绑定参数调用函数对象时,每个占位符 _N
被对应的第 N 个未绑定参数替换。
每个占位符如同以 extern /*unspecified*/ _1; 声明。 |
(C++17 前) |
鼓励实现如同以 inline constexpr /*unspecified*/ _1; 声明占位符,尽管标准仍然允许以 extern /*unspecified*/ _1; 声明它们。 |
(C++17 起) |
占位符对象的类型可默认构造
(DefaultConstructible)
且可复制构造 (CopyConstructible)
,其默认复制/移动构造函数不抛异常,且对于任何占位符 _N
,类型 std::is_placeholder<decltype(_N)> 有定义且从 std::integral_constant<int, N> 导出。
示例
下列代码展示以占位符参数创建函数对象。
#include <functional> #include <string> #include <iostream> 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(int argc, char* argv[]) { typedef std::function<void(const std::string&)> ExampleFunction; Object instance; std::string str("World"); ExampleFunction f = std::bind(&Object::hello, &instance, std::placeholders::_1); // 等价于 instance.hello(str) f(str); f = std::bind(&goodbye, std::placeholders::_1); // 等价于 goodbye(str) f(str); return 0; }
输出:
Hello World Goodbye World
参阅
(C++11)
|
绑定一或多个实参到函数对象 (函数模板) |
(C++11)
|
表明一个对象是标准占位符,或者可以用作标准占位符 (类模板) |
(C++11)
|
用 tie 解包
tuple 时用来跳过元素的占位符 (常量) |