如何在 C++ 中创建一个包含不同类型函数指针的容器?

How to create a container that holds different types of function pointers in C++?(如何在 C++ 中创建一个包含不同类型函数指针的容器?)

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

问题描述

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

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
", stack.pop());

你关注吗?

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

本文标题为:如何在 C++ 中创建一个包含不同类型函数指针的容器?