名稱空間
變體
操作

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

來自 cppreference.com
 
 
 
函式物件
部分函式應用
(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*)
(until C++17*)(until C++17*)(until C++17*)(until C++17*)
(直到 C++20*)
(直到 C++20*)
(直到 C++17*)(直到 C++17*)
(直到 C++17*)(直到 C++17*)

(直到 C++17*)
(until C++17*)(until C++17*)(until C++17*)(until C++17*)
(直到 C++20*)
(直到 C++20*)
 
定義於標頭檔案 <functional>
/*參見下文*/ _1;

/*參見下文*/ _2;
.
.

/*參見下文*/ _N;

std::placeholders 名稱空間包含佔位符物件 [_1, ..., _N],其中 N 是實現定義的上限值。

當在 std::bind 表示式中用作引數時,佔位符物件儲存在生成的函式物件中,當該函式物件透過未繫結引數呼叫時,每個佔位符 _N 會被相應的第 N 個未繫結引數替換。

每個佔位符都宣告為如同 extern /*未指定*/ _1;

(C++17 前)

鼓勵實現將佔位符宣告為如同 inline constexpr /*未指定*/ _1;,儘管標準仍然允許宣告為 extern /*未指定*/ _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 時跳過元素的佔位符
(常量) [編輯]