是否可以换出C ++中的基类?

时间:2019-04-07 17:15:27

标签: c++

说我有一个基类A1和派生类B1和B2。例如(人为):

Require Import Coq.Strings.String.

(* Prelude: the total_map data structure from Software Foundations, slightly modified *)
Definition total_map := string -> nat.
Definition empty_st : total_map := (fun _ => 0).
Definition t_update (m : total_map) k v := fun k' => if string_dec k k' then v else m k'.
Notation "a '!->' x" := (t_update empty_st a x) (at level 100).
Notation "x '!->' v ';' m" := (t_update m x v) (at level 100, v at next level, right associativity).

(* The actual goal I'm trying to solve *)
Definition X: string := "X".
Definition Y: string := "Y".
Goal forall n, (X !-> n; Y !-> n) <> (X !-> 1; Y !-> 2).
Proof.
  intros n contra.
  remember (X !-> n; Y !-> n) as st.
  remember (st X) as n1.
  assert (n1 = n). { rewrite Heqn1; rewrite Heqst; cbv; reflexivity. }
  assert (n1 = 1). { rewrite Heqn1; rewrite contra; cbv; reflexivity. }
  remember (st Y) as n2.
  assert (n2 = n). { rewrite Heqn2; rewrite Heqst; cbv; reflexivity. }
  assert (n2 = 2). { rewrite Heqn2; rewrite contra; cbv; reflexivity. }
  congruence.
Qed.

是否可以创建与B1和B2相同但从A2而不是A1派生的类C1和C2,而不必重新定义“ B”?即我只想将“ foo”换成C1和C2中的另一个函数,而无需重新定义如下:

class A1
{
public:
    int foo(int input);
};

class B1: public A1
{
public:
    int bar(int input) { return foo(input); }
};

class B2: public A1
{
public:
    int bar(int input) { return foo(foo(input)); }
};

1 个答案:

答案 0 :(得分:7)

1 是模板的用途:

template<class T>
struct Template : T
{
    int bar(int input) { return this->foo(input); }
};

using B1 = Template<A1>;

您可以使用包装器类,该包装器类以不同的名称委派成员函数:

struct A2Wrapper : A2 {
     int foo(int input) { return newfoo(input); }
};


using C1 = Template<A2Wrapper>;

1 即将类型替换为定义。