且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-12-29 08:10:08

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

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());

你关注吗?