首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::placeholders::_2

Defined in header <functional>

/*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)

占位符对象的类型为DefaultConstructibleCopyConstructible,它们的默认复制/移动构造函数不会引发异常,并且对于任何占位符_N,类型std::is_placeholder<decltype(_N)>定义并派生自std::integral_constant<int, N>...

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

二次

代码语言:javascript
复制
#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;
}

二次

产出:

二次

代码语言:javascript
复制
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)

代码语言:txt
复制
 © cppreference.com

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

扫码关注腾讯云开发者

领取腾讯云代金券