Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::bind

      From cppreference.com
      <cpp‎ |utility‎ |functional
       
       
      Utilities library
       
      Function objects
      Function invocation
      (C++17)(C++23)
      Identity function object
      (C++20)
      Old binders and adaptors
      (until C++17*)
      (until C++17*)
      (until C++17*)
      (until C++17*)  
      (until C++17*)
      (until C++17*)(until C++17*)(until C++17*)(until C++17*)
      (until C++20*)
      (until C++20*)
      (until C++17*)(until C++17*)
      (until C++17*)(until C++17*)

      (until C++17*)
      (until C++17*)(until C++17*)(until C++17*)(until C++17*)
      (until C++20*)
      (until C++20*)
       
      Defined in header<functional>
      template<class F,class...Args>
      /* unspecified */ bind( F&& f, Args&&...args);
      (1)(since C++11)
      (constexpr since C++20)
      template<class R,class F,class...Args>
      /* unspecified */ bind( F&& f, Args&&...args);
      (2)(since C++11)
      (constexpr since C++20)

      The function templatestd::bind generates a forwarding call wrapper forf. Calling this wrapper is equivalent to invokingf with some of its argumentsbound toargs.

      Ifstd::is_constructible<std::decay<F>::type, F>::value isfalse, orstd::is_constructible<std::decay<Arg_i>::type, Arg_i>::value isfalse for any typeArg_i inArgs, the program is ill-formed.

      Ifstd::decay<Ti>::type or any type inArgs is notMoveConstructible orDestructible, the behavior is undefined.

      Contents

      [edit]Parameters

      f -Callable object (function object, pointer to function, reference to function, pointer to member function, or pointer to data member) that will be bound to some arguments
      args - list of arguments to bind, with the unbound arguments replaced by theplaceholders_1,_2,_3... of namespacestd::placeholders

      [edit]Return value

      A function objectg of unspecified typeT, for whichstd::is_bind_expression<T>::value istrue. It has the following members:

      std::bindreturn type

      Member objects

      The return type ofstd::bind holds a member object of typestd::decay<F>::type constructed fromstd::forward<F>(f), and one object per each ofargs..., of typestd::decay<Arg_i>::type, similarly constructed fromstd::forward<Arg_i>(arg_i).

      Constructors

      The return type ofstd::bind isCopyConstructible if all of its member objects (specified above) are CopyConstructible, and isMoveConstructible otherwise. The type defines the following members:

      Member typeresult_type

      1)(deprecated in C++17) IfF is a pointer to function or a pointer to member function,result_type is the return type ofF. IfF is a class type with nested typedefresult_type, thenresult_type isF::result_type. Otherwise noresult_type is defined.
      2)(deprecated in C++17)result_type is exactlyR.
      (until C++20)

      Member functionoperator()

      Wheng is invoked in a function call expressiong(u1, u2, ...uM), an invocation of the stored object takes place, as if by

      1)INVOKE(fd,std::forward<V1>(v1),std::forward<V2>(v2), ...,std::forward<VN>(vN)), or
      2)INVOKE<R>(fd,std::forward<V1>(v1),std::forward<V2>(v2), ...,std::forward<VN>(vN)),

      wherefd is a value of typestd::decay<F>::type, the values and types of the bound argumentsv1,v2, ...,vN are determined as specifiedbelow.

      If some of the arguments that are supplied in the call tog() are not matched by any placeholders stored ing, the unused arguments are evaluated and discarded.

      An invocation ofoperator() isnon-throwingor is aconstant subexpression(since C++20) if and only if so is the underlyingINVOKE operation.operator() participates in overload resolution only if theINVOKE operation is well-formed when treated as an unevaluated operand.

      Ifg isvolatile-qualified, the program is ill-formed.

      IfINVOKE(fd, w1, w2, ..., wN) can never be a valid expression for any possible valuesw1,w2, ...,wN, the behavior is undefined.

      [edit]Bound arguments

      For each stored argumentarg_i, the corresponding bound argumentv_i in theINVOKE orINVOKE<R> operation is determined as follows:

      [edit]Case 1: reference wrappers

      Ifarg_i is of typestd::reference_wrapper<T> (for example,std::ref orstd::cref was used in the initial call tostd::bind), thenv_i isarg_i.get() and its typeV_i isT&: the stored argument is passed by reference into the invoked function object.

      [edit]Case 2: bind expressions

      Ifarg_i is of typeT for whichstd::is_bind_expression<T>::value istrue (for example, anotherstd::bind expression was passed directly into the initial call tostd::bind), thenstd::bind performs function composition: instead of passing the function object that the bind subexpression would return, the subexpression is invoked eagerly, and its return value is passed to the outer invokable object. If the bind subexpression has any placeholder arguments, they are shared with the outer bind (picked out ofu1,u2, ...). Specifically,v_i isarg_i(std::forward<Uj>(uj)...) and its typeV_i isstd::result_of<Tcv &(Uj&&...)>::type&&(until C++17)std::invoke_result_t<Tcv &, Uj&&...>&&(since C++17) (cv-qualification is the same as that ofg).

      [edit]Case 3: placeholders

      Ifarg_i is of typeT, for whichstd::is_placeholder<T>::value is not0 (meaning, a placeholder such asstd::placeholders::_1, _2, _3, ... was used as the argument to the initial call tostd::bind), then the argument indicated by the placeholder (u1 for_1,u2 for_2, etc) is passed to the invokable object:v_i isstd::forward<Uj>(uj) and its typeV_i isUj&&.

      [edit]Case 4: ordinary arguments

      Otherwise,arg_i is passed to the invokable object as lvalue argument:v_i is simplyarg_i and its typeV_i isTcv &, wherecv is the same cv-qualification as that ofg.

      [edit]Exceptions

      Only throws if construction ofstd::decay<F>::type fromstd::forward<F>(f) throws, or any of the constructors forstd::decay<Arg_i>::type from the correspondingstd::forward<Arg_i>(arg_i) throws whereArg_i is the ith type andarg_i is the ith argument inArgs... args.

      [edit]Notes

      As described inCallable, when invoking a pointer to non-static member function or pointer to non-static data member, the first argument has to be a reference or pointer (including, possibly, smart pointer such asstd::shared_ptr andstd::unique_ptr) to an object whose member will be accessed.

      The arguments to bind are copied or moved, and are never passed by reference unless wrapped instd::ref orstd::cref.

      Duplicate placeholders in the same bind expression (multiple_1's for example) are allowed, but the results are only well defined if the corresponding argument (u1) is an lvalue or non-movable rvalue.

      [edit]Example

      Run this code
      #include <functional>#include <iostream>#include <memory>#include <random> void f(int n1,int n2,int n3,constint& n4,int n5){std::cout<< n1<<' '<< n2<<' '<< n3<<' '<< n4<<' '<< n5<<'\n';} int g(int n1){return n1;} struct Foo{void print_sum(int n1,int n2){std::cout<< n1+ n2<<'\n';} int data=10;}; int main(){usingnamespacestd::placeholders;// for _1, _2, _3... std::cout<<"1) argument reordering and pass-by-reference: ";int n=7;// (_1 and _2 are from std::placeholders, and represent future// arguments that will be passed to f1)auto f1= std::bind(f, _2,42, _1,std::cref(n), n);    n=10;    f1(1,2,1001);// 1 is bound by _1, 2 is bound by _2, 1001 is unused// makes a call to f(2, 42, 1, n, 7) std::cout<<"2) achieving the same effect using a lambda: ";    n=7;auto lambda=[&ncref= n, n](auto a,auto b,auto/*unused*/){        f(b,42, a, ncref, n);};    n=10;    lambda(1,2,1001);// same as a call to f1(1, 2, 1001) std::cout<<"3) nested bind subexpressions share the placeholders: ";auto f2= std::bind(f, _3, std::bind(g, _3), _3,4,5);    f2(10,11,12);// makes a call to f(12, g(12), 12, 4, 5); std::cout<<"4) bind a RNG with a distribution: ";std::default_random_engine e;std::uniform_int_distribution<> d(0,10);auto rnd= std::bind(d, e);// a copy of e is stored in rndfor(int n=0; n<10;++n)std::cout<< rnd()<<' ';std::cout<<'\n'; std::cout<<"5) bind to a pointer to member function: ";    Foo foo;auto f3= std::bind(&Foo::print_sum,&foo,95, _1);    f3(5); std::cout<<"6) bind to a mem_fn that is a pointer to member function: ";auto ptr_to_print_sum=std::mem_fn(&Foo::print_sum);auto f4= std::bind(ptr_to_print_sum,&foo,95, _1);    f4(5); std::cout<<"7) bind to a pointer to data member: ";auto f5= std::bind(&Foo::data, _1);std::cout<< f5(foo)<<'\n'; std::cout<<"8) bind to a mem_fn that is a pointer to data member: ";auto ptr_to_data=std::mem_fn(&Foo::data);auto f6= std::bind(ptr_to_data, _1);std::cout<< f6(foo)<<'\n'; std::cout<<"9) use smart pointers to call members of the referenced objects: ";std::cout<< f6(std::make_shared<Foo>(foo))<<' '<< f6(std::make_unique<Foo>(foo))<<'\n';}

      Output:

      1) argument reordering and pass-by-reference: 2 42 1 10 72) achieving the same effect using a lambda: 2 42 1 10 73) nested bind subexpressions share the placeholders: 12 12 12 4 54) bind a RNG with a distribution: 0 1 8 5 5 2 0 7 7 10 5) bind to a pointer to member function: 1006) bind to a mem_fn that is a pointer to member function: 1007) bind to a pointer to data member: 108) bind to a mem_fn that is a pointer to data member: 109) use smart pointers to call members of the referenced objects: 10 10

      [edit]Defect reports

      The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

      DRApplied toBehavior as publishedCorrect behavior
      LWG 2021C++111. the bounded arguments
          were not forwarded tofd
      2. in case 2, the type ofV_i was
          std::result_of<Tcv (Uj...)>::type
      1. forwarded
      2. changed to
          std::result_of<Tcv &(Uj&&...)>::type&&

      [edit]See also

      (C++20)(C++23)
      bind a variable number of arguments, in order, to a function object
      (function template)[edit]
      placeholders for the unbound arguments in astd::bind expression
      (constant)[edit]
      (C++11)
      creates a function object out of a pointer to a member
      (function template)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/utility/functional/bind&oldid=173615"

      [8]ページ先頭

      ©2009-2025 Movatter.jp