Namespaces
Variants

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

来自 zh.cppreference.net
 
 
 
函数对象
函数调用
(C++17)(C++23)
恒等函数对象
(C++20)
透明运算符包装器
(C++14)
(C++14)
(C++14)
(C++14)  
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)
(C++14)

旧式绑定器与适配器
(直至 C++17*)
(直至 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>
/* see below */ _1;
/* see below */ _2;
.
.
/* see below */ _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 时跳过元素的占位符
(常量)