C++ 强制在子类中实现方法,但具有不同的签名 [英] C++ force implementation of method in child class but with a different signature

查看:36
本文介绍了C++ 强制在子类中实现方法,但具有不同的签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在子类中强制实现方法其中每个派生类的实现都有不同的签名?

Is there a way to force implementation of a method in a child class where the implementation will have a different signature for each derived class?

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

I know I can do this, using pure virtual:

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

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

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

Above, pure virtual getValue in the base class forces the derived class to implement getValue. But what I really want to do is something like this: Force each derived class to implement getValue() but each with a different signature:

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,编译器认为它们也是抽象的.

The problem with the above is that, due to name mangling, each signature is effectively a different function, and thus Derived_A and Derived_B inherit getValue() = 0 and the compiler thinks that they also are abstract.

我一直在尝试一些不同的方法来做到这一点,但在我看来没有办法做到这一点.我想我应该简单地在 Base 类中声明 getValue,然后确保每个派生类都实现它们的版本.

I've been playing around with some different ways to do this, but it appears to me there is no way to do it. I'm thinking I should simply not declare getValue in the Base class and then just make sure each derived class implements their version of it.

推荐答案

如果使用 CRTP 对你有用,你可以使用:

If use of CRTP would work for you, you can use:

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

这篇关于C++ 强制在子类中实现方法,但具有不同的签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆