0

我想制作一种可以执行特定任务的方法,并从内部进行简单的计算,例如加法、减法或乘法。如果我错了,请纠正我,似乎我无法直接传递此类操作的运算符,我需要定义一个中间方法(就像我的示例中的一个称为 operator_add )。我尝试使用以下代码完成我的任务:

struct A {
  typedef int T;
  /* (...) */
  struct element {
    /* (...) */
    inline T value() const { /* something simple */ };
    element& comp_assign( const T r, T (*operation)(const T, const T) ) { // line # 40
      T res = operation( value(), r );
      return modif_aux( res );
    } /* (...) */
    inline T operator_add( const T a, const T b ) { return a + b; }
    inline element& operator+=( const T r ) { return comp_assign( r, operator_add ); } // line # 64
  };
};

但我收到以下错误:

A.h:64: error: no matching function for call to ‘A::element::comp_assign(const int&, <unresolved overloaded function type>)’
A.h:40: note: candidates are: A::element& A::element::comp_assign(int, int (*)(int, int))
4

1 回答 1

0

operator_add是一个成员函数,因此您不能使用普通函数指针来引用它。将其设为静态函数或自由函数可以解决此问题,尽管我建议使用模板,因为它可以使用任何可调用对象:

template<typename Operation>
element& comp_assign( const T r, Operation operation) { // line # 40
  T res = operation( value(), r );
  return modif_aux( res );
}

inline element& operator+=( const T r ) { return comp_assign( r, std::plus<T>() ); }
于 2012-12-04T02:35:52.893 回答