"unresolved overloaded function type"错误并将运算符作为函数参数传递



我想制作一种方法来执行某项任务,并从内部进行简单的计算,例如加法,减法或乘法。如果我错了,请纠正我,似乎我无法直接传递此类操作的运算符,我需要定义一个中间方法(例如我示例中称为 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))

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

最新更新