将member-function作为参数传递给function-template

vag*_*rto 4 c++ templates member-function-pointers functor template-function

考虑在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;
}
Run Code Online (Sandbox Code Playgroud)

现在考虑一个模板函数来调用上面的三个函数:

template<class T>
void eval(T fun)
{
  fun("Using an external function");
}
Run Code Online (Sandbox Code Playgroud)

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) (...)’
Run Code Online (Sandbox Code Playgroud)

Pra*_*ian 7

指向成员函数的指针和指向函数的指针是两种不同的动物.前者采用隐式的第一个参数,this指针,或者换句话说,指向要在其上调用成员函数的实例的指针.

通常,为了能够将成员函数作为可调用对象传递,您bind将调用它的实例,然后用于placeholders指示稍后将传递给可调用对象的参数.在你的情况下

eval(std::bind(&FOO::m_function, &FUNCTOR, std::placeholders::_1));
Run Code Online (Sandbox Code Playgroud)

bind上面的第一个参数是指向要调用的成员函数的指针,第二个参数是指向要调用的FOO实例的指针m_function.最后一个是占位符,表示bind在调用成员函数时应该使用传递给创建的callable的第一个参数.

另一种方法是将lambda表达式传递给eval一个char const *(或std::string const&)参数并调用成员函数.

eval([](char const *c) { FUNCTOR.m_function(c); });
Run Code Online (Sandbox Code Playgroud)

现场演示

  • @vagoberto如果`m_function`保证不使用`FOO`的状态,那么**应该被声明为`static`,问题确实消失了.在创建没有状态的类之前总是要三思而后行:除非涉及到元编程,否则你真的想要一个命名空间. (2认同)