在线文档教程
C++
应用 | Utilities

std::placeholders::_N

STD::占位符:[医]1,STD::占位符::[医]2、...,STD::占位符::[医]n

Defined in header
/*see below*/ _1; /*see below*/ _2; . . /*see below*/ _N;

std::placeholders命名空间包含占位符对象。[_1, . . . _N]何地N是实现定义的最大数目。

当用作参数时,std::bind表达式,占位符对象存储在生成的函数对象中,当使用未绑定参数调用该函数对象时,每个占位符。_N被相应的Nth无界参数替换。

Each placeholder is declared as if by extern /*unspecified*/ _1;(until C++17)
Implementations are encouraged to declare the placeholders as if by inline constexpr /*unspecified*/ _1;, although declaring them by extern /*unspecified*/ _1; is still allowed by the standard.(since 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 // equivalent to instance.hello(str) f(str f = std::bind(&goodbye, std::placeholders::_1 // equivalent to goodbye(str) f(str return 0; }

二次

产出:

二次

Hello World Goodbye World

二次

另见

bind (C++11)binds one or more arguments to a function object (function template)
is_placeholder (C++11)indicates that an object is a standard placeholder or can be used as one (class template)

© cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

http://en.cppreference.com/w/cpp/实用程序/功能性/占位符