简体   繁体   English

指向C ++中的函数对象

[英]pointer to function object in C++

I wanted to pass a function object to a class, and the class will use the function object to do some job inside the class. 我想将一个函数对象传递给一个类,该类将使用函数对象在类中做一些工作。

But the problem is that, I don't what the function object will be passed in. So I figured that, define a void * pointer in the class, this pointer will be initialized with the function object which will be passed in. 但问题是,我不会传入函数对象。所以我想,在类中定义一个void *指针,这个指针将用传入的函数对象初始化。

Code goes below: 代码如下:

class A 
{
    public:
        //...
        void doSomeJob(int x)
        {
            (*functor)(x); //use the function object to process data x
        }

    private:
        //...
        void *functor; //function object's pointer will be assigned to this pointer
};

But the code doesn't work. 但代码不起作用。 I guess, can't use void *functor that way. 我想,不能用那种方式使用void *functor

I know I can use template class to finish the job, but my question is, can I still do the job using pointer to function object and how? 我知道我可以使用template class来完成这项工作,但我的问题是,我仍然可以使用pointer to function object完成工作吗?

PS PS

To make my problem clearer, there may be several function objects which differ from each other by how they process data, I don't what function object will be passed in, but I do know each of them will take a int parameter. 为了使我的问题更清楚,可能有几个函数对象因处理数据而彼此不同,我不会传递什么函数对象,但我知道每个函数对象都将采用一个int参数。

Just as some answers tell, I can do the job through function pointer , but function object has more utilities than function pointers, such as states , and that's what I'm gonna use. 正如一些答案所说,我可以通过function pointer完成工作,但是函数对象比函数指针有更多的实用工具,比如states ,这就是我要用的东西。

You can't call a function object of a type unknown to you at the call site if its type is not stored somewhere accessible to the call machinery. 如果呼叫机构的类型未存储在呼叫机构可访问的某个位置,则无法在呼叫站点调用未知类型的功能对象。

There are two options: 有两种选择:

If you can use C++11 or boost, you can use std::function resp. 如果你可以使用C ++ 11或boost,你可以使用std::function resp。 boost::function : boost::function

class A
{
public:
  // ...
  void doSomeJob(int x)
  {
    functor(x);
  }
private:
  std::function<void(int)> functor; // or boost::function when using boost
};

Here the type is stored (in an implicit form) inside the mechanism of the function template. 这里的类型(以隐式形式)存储在function模板的机制中。

Otherwise, if you can require that all function objects passed have a class type derived from a specific base class, you can create an abstract base class: 否则,如果您可以要求传递的所有函数对象都具有从特定基类派生的类类型,则可以创建抽象基类:

struct AbstractFunctor
{
  virtual void operator()(int) = 0;
};

class A
{
public:
  // ...
  void doSomeJob(int x)
  {
    (*functor)(x);
  }
private:
  AbstractFunctor* functor; // or boost::function when using boost
};

Here the type is stored in the virtual table of the function object. 这里的类型存储在函数对象的虚拟表中。

If you really can't use boost, you also might write a similar solution yourself. 如果你真的不能使用boost,你也可以自己编写类似的解决方案。 The key word is "type erasure", and it basically works by generating on the fly a derived object from a known base class (as in my second solution) which knows about your object's type and can call it. 关键词是“类型擦除”,它基本上通过动态生成来自已知基类的派生对象(如我的第二个解决方案),它知道对象的类型并可以调用它。 It might be done roughly as follows (untested code): 它可能大致如下(未经测试的代码):

class int_function
{
private:
  struct abstract_forward
  {
    virtual void call(int) = 0;
    virtual abstract_forward clone() const = 0;
    virtual ~abstract_forward() {}
  };
  template<typename Functor> struct forward: abstract_forward
  {
    forward(Functor f): func(f) {}
    void call(int i) { func(i); }
    abstract_forward clone() const { return new forward<Functor>(func); }
    Functor func;
  };
public:
  template<typename Functor> int_function(Functor f)
  {
    forwarder = new forward<Functor>(f);
  }
  int_function(int_function const& other)
  {
    forwarder = other.forwarder->clone();
  }
  int_function& operator=(int_function const& other)
  {
    abstract_forward* newfwd = other.forwarder->clone();
    delete forwarder;
    forwarder = newfwd;
  }
  ~int_function()
  {
    delete forwarder}
  }
  void operator()(int i)
  {
    forwarder->call(i);
  }
private:
  abstract_forward* forwarder;
};

class A
{
public:
  void doSomeJob(int x)
  {
    functor(x);
  }
private:
  int_function functor;
};
void *functor; //function object's pointer will be assigned to this pointer

This is not function pointer. 这不是函数指针。

What you need is this: 你需要的是这个:

void (*functor)(int); //function pointer

Even better is this (in C++11): 更好的是(在C ++ 11中):

#include <functional> //must include this 

std::function<void(int)> functor;

//then use it as:
functor(x);  //not (*functor)(x)

The correct syntax is: 正确的语法是:

void (*functor)(int);

Also see this tutorial for more about declaring and using function pointers: http://www.cprogramming.com/tutorial/function-pointers.html 有关声明和使用函数指针的更多信息,请参阅本教程: http//www.cprogramming.com/tutorial/function-pointers.html

C++ is very strict about its types, so you can't just use a void* as function pointer. C ++对其类型非常严格,因此您不能只使用void*作为函数指针。 The pointer must be an actual function pointer for you to call it. 指针必须是一个实际的函数指针,供您调用。

What do you mean you don't know what function object will be passed in? 你是什​​么意思,你不知道将传递什么功能对象? In that example, you know that it takes an int or int& as a parameter and probably returns void , for example, so you can store the function pointer as: 在该示例中,您知道它接受一个intint&作为参数,并且可能返回void ,例如,因此您可以将函数指针存储为:

void (*func)(int);

If you mean to say that you want to be able to store class member functions as well, or instances of classes that overload operator() , then you can use std::function and std::bind from <functional> if you have C++11, or boost::function and boost::bind : 如果你的意思是说你想要能够存储类成员函数,或者重载operator()的类的实例,那么如果你有C,你可以使用std::functionstd::bind from <functional> ++ 11,或boost::functionboost::bind

boost::function<void (int)> func;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM