我想将类成员函数作为模板参数传递,如main函数中的以下示例所示。能否请你帮忙?如果我将普通函数作为输入参数,它工作正常。

template <int n>
class meta
{
public:
  template <typename F1, typename F2>
  void operator()(F1& f1, F2& f2)
  {
     if (f2())
     {
       f1(n);
     }
  }
};

class temp
{
public:
  void func1(int x)
  {
     cout << "inside func1" << endl;
  }

  bool func2()
  {
    cout << "inside func2" << endl;
    return true;
  }
};


int main()
{
  temp t;

  meta<10>()(t.func1, t.func2);  //not working, func1 and func2 are class member functions

//meta<10>()(func1, func2);   //working, if func1 and func2 are normal functions (not part of the class)
}

最佳答案

如果要将成员函数作为参数传递,则可以将它们作为成员函数指针传递,但是还需要将该类型的对象传递给函数。 (如果没有对象,则没有要调用的成员函数)。
另外,请注意,调用成员函数的语法也不同:

template <typename T>
void operator()(T &t, void (T::*f1)(int), bool (T::*f2)())
{
   if ((t.*f2)())  // call member functions like this
   {
     (t.*f1)(n);
   }
}
现在您可以通过以下方式调用该函数:
meta<10>()(t, &temp::func1, &temp::func2);
这是demo

09-10 03:25
查看更多