考慮三種實現C++中的例程的方法:通過函子,成員函數和非成員函數。例如,將成員函數作爲參數傳遞給函數模板
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;
class FOO
{
public:
void operator() (string word) // first: functor
{
cout << word << endl;
}
void m_function(string word) // second: member-function
{
cout << word << endl;
}
} FUNCTOR;
void function(string word) // third: non-member function
{
cout << word << endl;
}
現在考慮一個模板函數來調用上面的三個功能:
template<class T>
void eval(T fun)
{
fun("Using an external function");
}
什麼叫FOO::m_function
通過EVAL的正確方法? 我想:
FUNCTOR("Normal call"); // OK: call to ‘void FOO::operator()(string)‘
eval(FUNCTOR); // OK: instantiation of ‘void eval(T) [with T = FOO]’
function("Normal call"); // OK: call to ‘void function(string)’
eval(function); // OK: instantiation of ‘void eval(T) [with T = void (*)(string)]’
FUNCTOR.m_function("Normal call"); // OK: call to member-function ‘FOO::m_function(string)’
eval(FUNCTOR.m_function); // ERROR: cannot convert ‘FOO::m_function’ from type
// ‘void (FOO::)(std::string) {aka void (FOO::)(string)}’
// to type ‘void (FOO::*)(std::basic_string<char>)’
// In instantiation of ‘void eval(T) [with T = void (FOO::*)(string)]’:
// ERROR: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘fun (...)’, e.g. ‘(... ->* fun) (...)’
'錯誤:必須使用或「 - > *」來調用指針到成員函數'請問錯誤消息該行給出提示「*」? – PaulMcKenzie
我想'的eval(T樂趣,O對象){對象。*的樂趣( 「... 」)}'沒有結果 – vagoberto
使用'(對象。*的樂趣)(「 ...」)'代替 – vsoftco