Namespaces
Variants

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

From cppreference.net
Utilities library
Function objects
Function invocation
(C++17) (C++23)
Identity function object
(C++20)
Old binders and adaptors
( until C++17* )
( until C++17* )
( until C++17* )
( until C++17* )
( until C++17* ) ( until C++17* ) ( until C++17* ) ( until C++17* )
( until C++20* )
( until C++20* )
( until C++17* ) ( until C++17* )
( until C++17* ) ( until C++17* )

( until C++17* )
( until C++17* ) ( until C++17* ) ( until C++17* ) ( until C++17* )
( until C++20* )
( until C++20* )
定义于头文件 <functional>
/*见下文*/ _1 ;

/*见下文*/ _2 ;
.
.

/*见下文*/ _N ;

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:: is_placeholder < decltype ( _N ) > 派生自 std:: integral_constant < int , N >

示例

以下代码展示了使用占位符参数创建函数对象的过程。

#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); // equivalent to instance.hello(str)
    f = std::bind(&goodbye, std::placeholders::_1);
    f(str); // equivalent to 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';
    };
    // binding the 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 时跳过元素的占位符
(常量)