std::placeholders::_1, std::placeholders::_2, ..., std::placeholders::_N
來自 cppreference.com
定義於標頭檔案 <functional> |
||
/*參見下文*/ _1; /*參見下文*/ _2; |
||
std::placeholders 名稱空間包含佔位符物件 [_1, ..., _N]
,其中 N
是實現定義的上限值。
當在 std::bind 表示式中用作引數時,佔位符物件儲存在生成的函式物件中,當該函式物件透過未繫結引數呼叫時,每個佔位符 _N
會被相應的第 N 個未繫結引數替換。
每個佔位符都宣告為如同 extern /*未指定*/ _1;。 |
(C++17 前) |
鼓勵實現將佔位符宣告為如同 inline constexpr /*未指定*/ _1;,儘管標準仍然允許宣告為 extern /*未指定*/ _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) |
指示一個物件是標準佔位符或可用作標準佔位符 (類模板) |
(C++11) |
使用 tie 解包 tuple 時跳過元素的佔位符(常量) |