在 c++ 中使用闭包更改行为

Changing behaviour using a closure in c++

本文关键字:闭包 c++      更新时间:2023-10-16

>我有一个基类和一个闭包,基类总是由特定的类扩展,但它没有确定基类具体包含什么。

现在我想在更改特定类的行为的同时覆盖基类的行为。

以下是我想要实现的目标的简单示例:

class base
{
    public:
        inline void print()
        {
            std::cout << "test!" << std::endl;
        }
};
template <class T>
class closure
{
    public:
        inline closure()
        {
            if (!std::is_convertible<T*, base*>::value) {
                throw "error!";
            }
            this->baseInstance = new T();
        }
        /*
         * In this class the behavior of test should be extended/overridden.
         * in this case base::print
        */
        ~closure()
        {
            delete this->baseInstance;
        }
        inline T * operator-> ()
        {
            return this->baseInstance;
        }
    private:
        T * baseInstance;
};
class test : public base
{
    public:
        inline void otherStuff()
        {
            /* ... **/
        }
        /* .. */
};

在这种情况下,我想覆盖base::print(),但在通过闭包调用test::otherStuff()时保持它的全部功能。

好的,我自己找到了解决方案。

最后很容易,因为我知道我想改变什么功能,我将基类的整个函数编写为std::function<void()>然后我与闭包交朋友,以便它能够覆盖它。

base::print()的方法调用已更改为std::function<void()>的调用,现在它运行良好。