C++多重继承静态函数调用歧义

标签 c++ templates multiple-inheritance

我有这样的情况:我从两个不同的基类派生一个类,这两个基类都有一个同名的静态函数。

为了解决这个歧义,我尝试使用范围运算符 - 就像我对成员函数所做的那样。但是这不能编译。为什么?语法错误?

我想通过派生类型名称调用静态函数,而不是直接通过基类名称。其实我更想避免这种情况,但我不知道该怎么做。

当我离开模板时,下面代码中的错误(已注释掉)也会发生:

#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;
}

最佳答案

制作“公告”protectedStaticBaseAStaticBaseB可能是做你想做的事情的一部分。

然后您就无法调用 StaticBaseB<NonDerived>::announce从 main 开始,因为它将无法访问。您可以从 StaticBaseB 派生的类中调用它。

换句话说:

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;
    }
};

在 Derived 中,您必须向公众宣传“公告”。

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
}

关于C++多重继承静态函数调用歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21434670/

相关文章:

c++ - (部分)特化依赖类型的非类型模板参数

python - 如何在 Python 3 中创建具体父类(super class)的抽象子类?

java - Play 中的 CConvertException!框架

java - Java中的多重继承设计问题

c++ - C++ 中 QObject 多重继承和策略/特征设计的问题

c++ - 使用 ofstream 打开文件时设置文件权限

c++ - 发出不同频率的声音

c++ - 确保创建线程并在广播前等待

c++ - std::u16string、std::u32string、std::string、length()、size()、码点和字符

c++ - 使用默认模板参数/参数与以下模板化函数有何区别