Mau*_*uez 1 c++ templates bind functor
我试图以这种方式使用旧的bind2nd函数:
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;
}
Run Code Online (Sandbox Code Playgroud)
但我收到很多错误:
required from 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 from here
error: no type named 'second_argument_type' in 'class printer<int>' typedef typename _Operation::second_argument_type _Arg2_type;
Run Code Online (Sandbox Code Playgroud)
从我所能看到的一切都是正确的,所以我真的不知道发生了什么.^
首先:我建议使用放弃bind1st()和bind2nd()在C + 11中弃用的,以及对C++ 03标准库的函数式编程的过时支持.
您应该使用C++ 11 std::bind(),因为您似乎可以负担得起 - 从您使用auto关键字的事实来判断:
#include <functional>
// ...
auto f1 = std::bind(printer<int>(), std::placeholders::_1, nme);
Run Code Online (Sandbox Code Playgroud)
这就是说,仅仅为了记录,不推荐使用的std::bind2nd()函数需要一些关于函子调用操作符签名的元数据,并且它希望这些元数据在functor类中作为类型别名提供.例如:
template<typename T>
class printer
{
public:
// These metadata must be present in order for bind1st and bind2nd to 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:
// // This could and should be
// // const-qualified
// ^^^^^
// Bonus advice #2: why not taking by
// reference to const here? ;)
{
cout<<a<<endl;
}
};
Run Code Online (Sandbox Code Playgroud)
实现上述目标的一种更简单的方法是使用(也已弃用)类模板std::binary_function作为基类,并让该类模板定义适当的类型别名:
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;
}
};
Run Code Online (Sandbox Code Playgroud)
但同样,请考虑放入std::bind1st(),std::bind2nd()以及,std::unary_function并且std::binary_function,回到抽屉里.它们被C++ 11对函数式编程的更强大支持所取代.
| 归档时间: |
|
| 查看次数: |
2268 次 |
| 最近记录: |