考虑三种实现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