C++ 中指向函数对象的指针

发布于 2024-12-27 05:28:47 字数 772 浏览 0 评论 0原文

我想将函数对象传递给类,类将使用函数对象在类内部完成一些工作。

但问题是,我不知道函数对象将传入什么。所以我想,在类中定义一个 void * 指针,这个指针将用函数对象初始化将被传入。

代码如下:

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
};

但代码不起作用。我想,不能这样使用 void *functor

我知道我可以使用模板类来完成这项工作,但我的问题是,我仍然可以使用指向函数对象的指针来完成这项工作以及如何完成?

PS

为了让我的问题更清楚,可能有几个函数对象在处理数据的方式上彼此不同,我不知道将传入什么函数对象,但我确实知道它们中的每一个将采用 int 参数。

正如一些答案所说,我可以通过函数指针来完成这项工作,但是函数对象比函数指针有更多的实用程序,例如状态,这就是我要做的使用。

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.

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.

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?

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.

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

权谋诡计 2025-01-03 05:28:47

如果某个函数对象的类型没有存储在调用机制可访问的某处,那么您就无法在调用站点调用您未知类型的函数对象。

有两个选项:

如果您可以使用 C++11 或 boost,则可以分别使用 std::functionboost::function

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

此处类型存储(以隐式形式)在function 模板的机制内。

否则,如果您可以要求传递的所有函数对象都具有从特定基类派生的类类型,则可以创建一个抽象基类:

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
};

这里类型存储在函数对象的虚拟表中。

如果你确实不能使用boost,你也可以自己写一个类似的解决方案。关键词是“类型擦除”,它基本上是通过从已知基类(如我的第二个解决方案中)动态生成派生对象来工作的,该基类知道对象的类型并可以调用它。大致可以按如下方式完成(未经测试的代码):

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;
};

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. 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.

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. 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;
};
风渺 2025-01-03 05:28:47
void *functor; //function object's pointer will be assigned to this pointer

这不是函数指针。

你需要的是这样的:

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

更好的是(在 C++11 中):

#include <functional> //must include this 

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

//then use it as:
functor(x);  //not (*functor)(x)
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):

#include <functional> //must include this 

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

//then use it as:
functor(x);  //not (*functor)(x)
呆头 2025-01-03 05:28:47

正确的语法是:

void (*functor)(int);

另请参阅本教程以了解有关声明和使用函数指针的更多信息: http:// /www.cprogramming.com/tutorial/function-pointers.html

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

盗心人 2025-01-03 05:28:47

C++对其类型非常严格,因此不能仅使用void*作为函数指针。该指针必须是实际的函数指针才能调用它。

你不知道将传入什么函数对象是什么意思?在该示例中,您知道它采用 intint& 作为参数,并且可能返回 void,例如,因此您可以存储函数指针为:

void (*func)(int);

如果您的意思是说您还希望能够存储类成员函数,或者重载 operator() 的类实例,那么您可以使用 std: :函数std::bind 来自 (如果您使用的是 C++11),或者 boost::functionboost::bind

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

C++ is very strict about its types, so you can't just use a void* as function pointer. 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:

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:

boost::function<void (int)> func;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文