如何创建一个容器,在C ++中保存不同类型的函数指针? [英] How to create a container that holds different types of function pointers in C++?

查看:200
本文介绍了如何创建一个容器,在C ++中保存不同类型的函数指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个线性遗传编程项目,其中程序是通过自然进化机制进化和演化的。他们的DNA基本上是一个容器(我已经使用数组和向量成功),其中包含一组函数可用的函数指针。
现在,对于简单的问题,例如数学问题,我可以使用一个类型定义的函数指针,它可以指向所有返回double的函数,并且所有函数都作为参数使用两次。

I'm doing a linear genetic programming project, where programs are bred and evolved by means of natural evolution mechanisms. Their "DNA" is basically a container (I've used arrays and vectors successfully) which contain function pointers to a set of functions available. Now, for simple problems, such as mathematical problems, I could use one type-defined function pointer which could point to functions that all return a double and all take as parameters two doubles.

不幸的是这不是很实用。我需要能够有一个容器,它可以有不同种类的函数指针,例如一个函数指针指向一个不带参数的函数,或者一个函数接受一个参数,或者一个函数返回某个东西,等等(你得到想法)...

Unfortunately this is not very practical. I need to be able to have a container which can have different sorts of function pointers, say a function pointer to a function which takes no arguments, or a function which takes one argument, or a function which returns something, etc (you get the idea)...

有任何方法使用任何类型的容器吗?
我可以使用一个包含多态类的容器,它们又有各种各样的函数指针?
我希望有人可以指导我去解决方案,因为重新设计我到目前为止做的一切都会很痛苦。

Is there any way to do this using any kind of container ? Could I do that using a container which contains polymorphic classes, which in their turn have various kinds of function pointers? I hope someone can direct me towards a solution because redesigning everything I've done so far is going to be painful.

推荐答案

虚拟机的一个典型的想法是有一个单独的堆栈,用于参数和返回值传递。

A typical idea for virtual machines is to have a separate stack that is used for argument and return value passing.

你的函数仍然可以是类型void fn (void),但您可以手动传递和手动返回参数。

Your functions can still all be of type void fn(void), but you do argument passing and returning manually.

您可以这样做:

class ArgumentStack {
    public:
        void push(double ret_val) { m_stack.push_back(ret_val); }

        double pop() {
             double arg = m_stack.back();
             m_stack.pop_back();
             return arg;
        }

    private:
        std::vector<double> m_stack;
};
ArgumentStack stack;

...所以一个函数可能如下所示:

...so a function could look like this:

// Multiplies two doubles on top of the stack.
void multiply() {
    // Read arguments.
    double a1 = stack.pop();
    double a2 = stack.pop();

    // Multiply!
    double result = a1 * a2;

    // Return the result by putting it on the stack.
    stack.push(result);
}

这样可以使用:

// Calculate 4 * 2.
stack.push(4);
stack.push(2);
multiply();
printf("2 * 4 = %f\n", stack.pop());

你跟着吗?

这篇关于如何创建一个容器,在C ++中保存不同类型的函数指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆