如果在 C++ 中有多个继承模板,则非法调用非静态成员函数

Illegal Call of Nonstatic Member Function if Multiple Inheriting Templates in C++

我的主机有 2 个策略,每个策略都有一个 print 函数。 如果我调用 Policy::print(),没有问题,但如果我调用 OtherPolicy::print(),就会出现错误。

Error   C2352    'OtherPolicy<T,Host<T,SubPolicy,OtherPolicy>>::printer': illegal call of non-static member function
        with
        [
            T=uint32_t
        ]   Scratch D:\tmp\ScratchCpp\Scratch\Scratch\HostPolicy.h  63  
#include <iostream>

template<
    typename T,
    class Host
>
class Policy {
public:
    virtual void printer()
    {
        std::cout << "base policy" << std::endl;
    }
};

template<
    typename T,
    class Host
>
class SubPolicy : Policy<T, Host> {
public:
    void printer() override
    {
        auto host = static_cast<Host&>(*this);
        std::cout << "sub policy" << std::endl;
    }
};

template<
    typename T,
    class Host
>
class OtherPolicy {
public:
    void printer()
    {
        auto host = static_cast<Host&>(*this);
        std::cout << "other policy" << std::endl;
    }
};

template<
    typename T,
    template<typename, class> class A,
    template<typename, class> class B
>
class Host :
    public A<T, Host<T, A, B>>,
    public B<T, Host<T, Policy, B>> {
public:
    void printer()
    {
        std::cout << "host" << std::endl;
        A<T, Host>::printer();
        B<T, Host>::printer(); // comment out this line to compile successfully
    }
};

int main(int argc, char **argv)
{
    Host<uint32_t, SubPolicy, OtherPolicy> host;
    host.printer();
}

有人能解释一下这是怎么回事以及如何正确地做到这一点吗?

Host 的第二个碱基 class 的类型是 B<T, Host<T, Policy, B>> 不是 B<T, Host>。这会导致错误,因为 B<T, Host> 不是 Host 的基础 class。

修复方法是正确命名基的类型 class:

B<T, Host<T, Policy, B>>::printer();