简体   繁体   English

函子重载最佳做法

[英]functor overloading best practices

Hi I am trying to get to grips with functors. 嗨,我试图与函子交手。 Here is a simple example 这是一个简单的例子

struct A {
 double b,c;
 A(const double bb, const double cc) : b(bb), c(cc) {}
 double operator()(const double x, const double y) {
  return b*c*x*y;
 }
};

I would like to know if it is possible to overload A such that it could be passed b , c and also eg x reusing the code in the operator() . 我想知道是否有可能使A重载,以便可以将其传递给bc ,还可以例如x重用operator()的代码。 My overall interest is to not have to re-write lengthy code in operators multiple times and to better understand the best practices for doing this. 我的总体兴趣是不必在操作员中多次重写冗长的代码,而不必更好地了解执行此操作的最佳实践。

Thanks! 谢谢!

One method of doing this is with std::bind in <functional> . 一种实现方法是使用<functional> std::bind This returns a closure that you can call without arguments. 这将返回一个不带参数的闭包。 An alternative would be to create a new constructor with default arguments for a and b , or a derived class, and overload it to have: 一种替代方法是使用ab或派生类的默认参数创建一个新的构造函数,并将其重载为:

double operator()(const double x = m_x, const double y = m_y);

As a side note, please don't use the same names for members and arguments of member functions; 附带说明一下,请不要为成员和成员函数的参数使用相同的名称; that creates ambiguity about which you mean and could even cause bugs if you rename a parameter later. 这会造成含糊不清的含义,如果稍后重命名参数,甚至可能导致错误。

I would like to know if it is possible to overload A such that it could be passed b, c and also eg x reusing the code in the operator(). 我想知道是否有可能使A重载,以便可以将其传递给b,c以及例如x重用operator()中的代码。

Yes, it is not difficult to do that. 是的,这样做并不难。

double operator()(double x, double y) // Remove the const. It's useless.
{
   // Call the other overload using the member data.
   return (*this)(b, c, x, y);
}

double operator()(double bb, double cc, double x, double y)
{
   // Not using any member data at all.
   return bb*cc*x*y;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM