函子重载最佳做法

问题描述 投票:1回答:2

嗨,我试图与函子交手。 这是一个简单的例子

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;
 }
};

我想知道是否有可能使A重载,以便可以将其传递给bc ,还可以例如x重用operator()的代码。 我的总体兴趣是不必在操作员中多次重写冗长的代码,而不必更好地了解执行此操作的最佳实践。

谢谢!

c++ operator-overloading operator-keyword functor
2个回答
0
投票

一种实现方法是使用<functional> std::bind 。 这将返回一个不带参数的闭包。 一种替代方法是使用ab或派生类的默认参数创建一个新的构造函数,并将其重载为:

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

附带说明一下,请不要为成员和成员函数的参数使用相同的名称; 这会造成含糊不清的含义,如果稍后重命名参数,甚至可能导致错误。


0
投票

我想知道是否有可能使A重载,以便可以将其传递给b,c以及例如x重用operator()中的代码。

是的,这样做并不难。

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.