繁体   English   中英

C ++强制在子类中实现方法,但签名不同

[英]C++ force implementation of method in child class but with a different signature

有没有一种方法可以强制在子类中实现方法,而子类的实现对每个派生类都有不同的签名?

我知道我可以使用纯虚拟机做到这一点:

class Base {
  public:
   virtual void getValue(string& s) = 0;
}

class Derived : public Base {
  public:
   void getValue(string& s);
}

上面,基类中的纯虚拟getValue强制派生类实现getValue。 但是我真正想做的是这样的:强制每个派生类实现getValue(),但是每个都有不同的签名:

class Base {
  public:
   void getValue() = 0;
}

class Derived_A : public Base {
  public:
   void getValue(string& s);
}

class Derived_B : public Base {
  public:
   void getValue(int *j);
}

上面的问题是,由于名称处理,每个签名实际上是一个不同的函数,因此Derived_A和Derived_B继承了getValue()= 0,并且编译器认为它们也是抽象的。

我一直在尝试一些不同的方法来执行此操作,但是在我看来,没有任何方法可以执行此操作。 我想在基类我根本就没有申报的getValue然后只需确保每一个派生类实现自己的版本,它。

如果可以使用CRTP ,则可以使用:

#include <string>

template <typename TypeSelector>
class Base {
  public:
     using type = typename TypeSelector::type;
     virtual void getValue(type t) = 0;
};

struct TypeSelector_A {
   using type = std::string&;
};

class Derived_A : public Base<TypeSelector_A> {
   public:
      void getValue(std::string& s) { /* Add real implementation */ }
};

struct TypeSelector_B {
   using type = int*;
};

class Derived_B : public Base<TypeSelector_B> {
   public:
      void getValue(int* j) { /* Add real implementation */ }
};

int main()
{
   Derived_A a;
   Derived_A b;
}

但是我真正想做的是这样的:强制每个派生类实现getValue(),但是每个都有不同的签名

具有虚拟函数(是否抽象)的全部要点是,可以将其与指针或对基类的引用一起使用,这意味着您将使用基类中的函数签名。 有了那个,你想要的东西是完全没有用的。 您可以通过返回std::variantstd::any与树中的每个虚函数一起实现,从而使签名保持不变。

您应该考虑如果可能的话,将如何使用这种概念。 如果您这样想:

void foo( Base *b ) {
    if( auto *d = dynamic_cast<Derived_A *>( b ) ) {
       std::string str;
       d->getValue( str );
       ...
    }
    if( auto *d = dynamic_cast<Derived_B *>( b ) ) {
       int i = 0;
       d->getValue( &i );
       ...
    }
}

那么getValue()不必是虚拟的,您只需要在Base虚拟分隔符即可。 但这被认为是不好的设计。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM