gpt4 book ai didi

C++ 仿函数绑定(bind)

转载 作者:行者123 更新时间:2023-11-30 00:53:23 24 4
gpt4 key购买 nike

我尝试以这种方式使用旧的 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_functionstd::binary_function,回到抽屉里。它们被 C++11 对函数式编程更强大的支持所取代。

关于C++ 仿函数绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16625509/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com