我有一个具有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();
}
有人会好心地解释正在发生的事情以及如何正确执行此操作吗?
答案 0 :(得分:2)
Host
的第二个基类的类型为B<T, Host<T, Policy, B>>
,不是 B<T, Host>
。由于B<T, Host>
不是Host
的基类,因此会导致错误。
解决方法是正确命名基类的类型:
B<T, Host<T, Policy, B>>::printer();