templates - C++ functor binding -
i tried use old bind2nd function in way:
template<typename t> class printer { public: void operator()(t a, string& kd) { cout<<a<<endl; } }; int main(int argc, char *argv[]) { string nme = "j-dar"; auto f1 = bind2nd(printer<int>(),nme); //f1(5); return 0; }
but lot of errors:
required here error: no type named 'first_argument_type' in 'class printer<int>' class binder2nd ^ error: no type named 'second_argument_type' in 'class printer<int>' typename _operation::second_argument_type value; ^ error: no type named 'second_argument_type' in 'class printer<int>' binder2nd(const _operation& __x, ^ error: no type named 'result_type' in 'class printer<int>' operator()(const typename _operation::first_argument_type& __x) const ^ error: no type named 'result_type' in 'class printer<int>' operator()(typename _operation::first_argument_type& __x) const ^ required here error: no type named 'second_argument_type' in 'class printer<int>' typedef typename _operation::second_argument_type _arg2_type;
from can see it's correct don't know going on. ^
first of all: recommend using abandoning bind1st()
, bind2nd()
, deprecated in c+11, , in general obsolete support functional programming of c++03 standard library.
you should rather use c++11's std::bind()
, since seems can afford - judging fact using auto
keyword:
#include <functional> // ... auto f1 = std::bind(printer<int>(), std::placeholders::_1, nme);
this said, record, deprecated std::bind2nd()
function requires metadata signature of functor's call operator, , expects these metadata provided type aliases in functor class. instance:
template<typename t> class printer { public: // these metadata must present in order bind1st , bind2nd work... typedef void result_type; typedef t first_argument_type; typedef string const& second_argument_type; void operator()(t a, string const& kd) const // ^^^^^ // bonus advice #1: // // , should // // const-qualified // ^^^^^ // bonus advice #2: why not taking // reference const here? ;) { cout<<a<<endl; } };
a simpler way of achieving above use (also deprecated) class template std::binary_function
base class, , let class template define appropriate type aliases:
template<typename t> class printer : public std::binary_function<t, string const&, void> // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ { public: void operator()(t a, string const& kd) const { cout<<a<<endl; } };
but again, please consider putting std::bind1st()
, std::bind2nd()
, std::unary_function
, std::binary_function
, in drawer. superseded c++11's more powerful support functional programming.
Comments
Post a Comment