functional_placeholders
functional_placeholders (자리 표시자 객체)
이 페이지는 <functional> 헤더의 std::placeholders 네임스페이스에 정의된 자리 표시자(placeholder) 객체들에 대해 설명해요. std::bind 표현식에서 인자로 사용되어, 나중에 함수 객체를 호출할 때 전달되는 인자 중 해당 위치를 채우는 역할을 해요. C++11부터 표준으로 제공되며, 최대 개수는 구현에 따라 정의돼요.
출처: cppreference
본문
<functional> 헤더에 다음과 같이 선언돼 있어요.
<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>에서 파생돼요.
예제 (Example)
다음 코드는 자리 표시자 인자를 사용해 함수 객체를 만드는 방법을 보여줘요.
#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");
}
출력 (Output):
Hello World
Goodbye World
Goooooooogol
같이 보기 (See also)
bind (C++11) |
함수 객체에 하나 이상의 인자를 바인딩해요 (함수 템플릿) [edit] |
|---|---|
is_placeholder (C++11) |
객체가 표준 자리 표시자이거나 자리 표시자로 사용될 수 있음을 나타내요 (클래스 템플릿) [edit] |
ignore (C++11) |
tie로 튜플을 풀 때 요소를 건너뛰기 위한 자리 표시자예요 (상수) [edit] |