2012-12-04 26 views
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)) 

回答

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

,我怎麼會叫comp_assign加法? –

+0

@infoholic_anonymous我在代碼中展示了它。使用'std :: plus'。 – Pubby

+0

我不好,抱歉。我是一個真正的新手,當涉及到模板時,我認爲我需要在函數名稱後面直接使用不等式符號括號(<>)...無論如何,非常感謝! –

相關問題