命名空间
变体
操作

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

来自 cppreference.cn
< cpp‎ | utility‎ | functional
 
 
 
函数对象
偏函数应用
(C++20)(C++23)
(C++11)
_1, _2, _3, ...
(C++11)
函数调用
(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>
/*见下文*/ _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 起)

占位符对象的类型是 DefaultConstructibleCopyConstructible,它们的默认复制/移动构造函数不会抛出异常,并且对于任何占位符 _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 时跳过元素的占位符
(常量) [编辑]