我的情况是我从两个不同的基类派生一个类,它们都有一个同名的静态函数。
为了解决这种歧义,我尝试使用范围运算符 - 就像我对成员函数所做的那样。但是这不编译。 为什么?语法错误?
我想通过派生的typename调用静态函数,而不是直接通过基类名称。其实我更愿意预防这种情况,但我不知道该怎么做。
当我离开模板时,下面的代码中也会出现错误(已注释掉):
#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;
}
答案 0 :(得分:1)
制作&#34;宣布&#34; protected
StaticBaseA
和StaticBaseB
中的StaticBaseB<NonDerived>::announce
可能会成为你想做的事情的一部分。
然后你无法从main调用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;
}
};
,因为它无法访问。您可以从派生自StaticBaseB的类中调用它。
换句话说:
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
}
在Derived中你必须宣传&#34;宣布&#34;公开。
{{1}}