std::placeholders::_1, std::placeholders::_2, ..., std::placeholders::_N

来自cppreference.com
< cpp‎ | utility‎ | functional
 
 
 
函数对象
部分函数应用
(C++20)(C++23)
(C++11)
_1, _2, _3, ...
(C++11)
函数调用
(C++17)(C++23)
恒等函数对象
(C++20)
旧式绑定器与适配器
(C++17 前*)
(C++17 前*)
(C++17 前*)
(C++17 前*)
(C++17 前*)(C++17 前*)(C++17 前*)(C++17 前*)
(C++20 前*)
(C++20 前*)
(C++17 前*)(C++17 前*)
(C++17 前*)(C++17 前*)

(C++17 前*)
(C++17 前*)(C++17 前*)(C++17 前*)(C++17 前*)
(C++20 前*)
(C++20 前*)
 
在标头 <functional> 定义
/* 见下文 */ _1;

/* 见下文 */ _2;
.
.

/* 见下文 */ _N;

std::placeholders 命名空间含有占位对象 [_1, . . . _N],其中 N 是实现定义的最大数字。

当用作 std::bind 表达式中的实参时,占位符对象被存储于生成的函数对象中,而以未绑定实参调用函数对象时,每个占位符 _N 被对应的第 N 个未绑定实参替换。

每个占位符如同以 extern/* 未指明 */ _1; 声明。

(C++17 前)

鼓励实现如同以 inlineconstexpr/* 未指明 */ _1; 声明占位符,尽管标准仍然允许以 extern/* 未指明 */ _1; 声明它们。

(C++17 起)

占位符对象的类型可默认构造(DefaultConstructible) 可复制构造(CopyConstructible) ,其默认复制/移动构造函数不抛异常,且对于任何占位符 _N,类型 std::is_placeholder<decltype(_N)> 有定义且从 std::integral_constant<int, N> 派生。

[编辑]示例

下列代码展示以占位符实参创建函数对象。

#include <functional>#include <iostream>#include <string>   void goodbye(conststd::string& s){std::cout<<"Goodbye "<< s <<'\n';}   class Object {public:void hello(conststd::string& s){std::cout<<"Hello "<< s <<'\n';}};   int main(){usingnamespace std::placeholders;   using ExampleFunction =std::function<void(conststd::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)
tie 解包 tuple 时用来跳过元素的占位符
(常量)[编辑]
close