[英]“unresolved overloaded function type” error and passing an operator as a function argument
我想制作一個可以執行特定任務的方法,並從內部進行簡單的計算,例如加法,減法或乘法。 如果我錯了,請糾正我,似乎我無法直接傳遞此類操作的運算符,而我需要定義一個中間方法(例如在我的示例中稱為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>() ); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.