作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我尝试以这种方式使用旧的 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;
}
但是我得到了很多错误:
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;
据我所知,这一切都是正确的,所以我真的不知道发生了什么。 ^
最佳答案
首先:我建议放弃 bind1st()
和 bind2nd()
,它们在 C+11 中已弃用,并且一般来说,C++03 标准库对函数式编程的过时支持。
您应该使用 C++11 的 std::bind()
,因为您似乎负担得起 - 从您使用 auto
关键字的事实来看:
#include <functional>
// ...
auto f1 = std::bind(printer<int>(), std::placeholders::_1, nme);
这就是说,只是为了记录,已弃用的 std::bind2nd()
函数需要一些关于仿函数调用运算符签名的元数据,并且它希望这些元数据作为类型别名提供在你的仿函数类中。例如:
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;
}
};
实现上述目标的一种更简单的方法是使用(也已弃用)类模板 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;
}
};
但同样,请考虑放置 std::bind1st()
、std::bind2nd()
以及 std::unary_function
和 std::binary_function
,回到抽屉里。它们被 C++11 对函数式编程更强大的支持所取代。
关于C++ 仿函数绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16625509/
我是一名优秀的程序员,十分优秀!