[英]C++ multiple inheritance static function call ambiguity
I have the case where I am deriving a class from two different base classes both having a static function with the same name. 我遇到的情况是,我从两个不同的基类派生了一个类,它们都具有一个具有相同名称的静态函数。
To resolve this ambiguity, I tried to use the scope operator - just as I would do for a member function. 为了解决这种歧义,我尝试使用范围运算符-就像对成员函数一样。 However This does not compile.
但是,这不会编译。 Why?
为什么? Wrong syntax?
语法错误?
I want to call the static function via the derived typename and not directly via base class name. 我想通过派生的类型名而不是直接通过基类名来调用静态函数。 Actually I would like prefer to prevent this case, but I have no idea how to do so.
实际上,我想防止这种情况发生,但是我不知道该怎么做。
The error (commented out) in the code below also occurs, when I leave the templates away: 当我离开模板时,下面的代码中的错误(注释掉)也会发生:
#include <iostream>
template<class TDerived>
class StaticBaseA
{
public:
static void announce()
{
std::cout << "do something" << std::endl;
}
};
template<class TDerived>
class StaticBaseB
{
public:
static void announce()
{
std::cout << "do something else" << std::endl;
}
};
class Derived :
public StaticBaseA<Derived>
, public StaticBaseB<Derived>
{
using StaticBaseA<Derived>::announce;
};
class NonDerived {};
int main(int argc, char* argv[])
{
Derived::announce();
// What I want:
//Derived::StaticBaseB<Derived>::announce(); Error: "Undefined symbol 'StaticBaseB'
// What works, but what I don't want ...
StaticBaseB<Derived>::announce();
// ... because I would like to prevent this (however this is done):
StaticBaseB<NonDerived>::announce();
return 0;
}
Making "announce" protected
in StaticBaseA
and StaticBaseB
might be part-way to doing what you want. 在
StaticBaseA
和StaticBaseB
“公告”进行protected
可能是完成所需操作的一部分。
You then could not call StaticBaseB<NonDerived>::announce
from main as it would be inaccessible. 然后,您将无法从main调用
StaticBaseB<NonDerived>::announce
,因为它将无法访问。 You could call it from a class derived from StaticBaseB. 您可以从从StaticBaseB派生的类中调用它。
In other words: 换一种说法:
template<class TDerived>
class StaticBaseA
{
protected:
static void announce()
{
std::cout << "do something" << std::endl;
}
};
template<class TDerived>
class StaticBaseB
{
protected:
static void announce()
{
std::cout << "do something else" << std::endl;
}
};
In Derived you have to promote "announce" to public. 在“派生”中,您必须向公众宣传“公告”。
class Derived : public StaticA<Derived>, public StaticB<Derived >
{
public:
using StaticA<Derived>::announce;
};
int main()
{
Derived::announce(); // legal and calls StaticBaseA::announce
NotDerived::announce(); // no such function
StaticBaseA< Derived >::announce(); // not accessible
StaticBaseB< Derived >::announce(); // also not accessible
StaticBaseA< NotDerived >::announce(); // not accessible
StaticBaseB< NotDerived >::announce(); // also not accessible
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.