从Lambda中调用虚拟父保护功能

时间:2015-01-04 01:04:10

标签: c++ c++11 lambda

如何在受保护的情况下使用lambda调用虚拟父函数?

template<typename T>
class Parent
{
    protected:
        virtual int Show()
        {
            std::cout<<"Parent::Show Called\n";
        }
};

class Child : Parent<Child>
{
    protected:
        virtual int Show() final override
        {
            std::cout<<"Child::Show Called\n";

            //supposed to be in a thread in my original code.
            auto call_parent = [&] {
                //Parent<Child>::Create(); //call other parent functions..
                Parent<Child>::Show();
            };

            call_parent();
        }
};

我得到的错误是:

错误:'int Parent :: Show()[with T = Child]'在此上下文中受到保护

有什么想法吗?我在Windows上使用GCC / G ++ 4.8.1。

1 个答案:

答案 0 :(得分:5)

作为解决方法,您可以通过蹦床调用Parent<Child>::Show()函数:

class Child : Parent<Child>
{
    int trampoline() {
        return this->Parent<Child>::Show();
    }
protected:
    virtual int Show() final override
    {
        std::cout<<"Child::Show Called\n";
        auto call_parent = [&] {
            this->trampoline();
        };
        call_parent();
        return 0;
    }
};