首页 > 解决方案 > 架构模式:处理两个相同实现的函数

问题描述

我有以下问题,鉴于我面临的问题,我想我解决的方法不正确:

我有一个接口I和实现,A, B, C...我想以某种方式表达我可以从夫妻(f(A,A),f(B,B),f(C,C))等等中得到一些结果。换句话说,我想接口 I 来表达两个相同的实现可以组合产生一些结果,而另一些则不能(你不能从 f(A, B) 得到任何有效的结果)。

现在我有以下内容:

#include <iostream>

using namespace std;
class A;
class B;
class I{
public:
  virtual int f (const I &other) const = 0;
  virtual int fSpecific (const A &other) const { throw runtime_error(""); };
  virtual int fSpecific (const B &other) const { throw runtime_error(""); };
};

class A: public I{

public:
 A(int a) : a(a) {} 
 int f (const I &other) const override { other.fSpecific(*this); }
 int fSpecific (const A &other) const override { /*logic here*/ return a + other.a; }
 int a;
};

class B: public I{

public:
 B(int b1, int b2) : b1(b1), b2(b2) {}
 int f (const I &other) const override { other.fSpecific(*this); }
 int fSpecific (const B &other) const override { /*logic here*/ return b1*b1 + b2*b2 + other.b1*other.b1 + other.b2*other.b2; }
private:
 int b1;
 int b2;
};

int f(const I &a, const I &b) {
    a.f(b);
}

int main()
{
    cout << f(A(1), A(2)) << std::endl; // prints 3
    cout << f(B(1, 2), B(3, 4)) << std::endl; // prints 30
    cout << f(A(1), B(3, 4)) << std::endl; // throws an error

    return 0;
}
/*and so on*/

但我想我使用了错误的架构。因为添加类会导致I. 有没有更好的解决方案来表达这种关系?

标签: c++design-patternsarchitecture

解决方案


您可以雇用dynamic_cast

class I {
public:
    template<typename T>
    void fSpecific (T &other) {
        if (dynamic_cast<T*>(this))
            std::cout << "OK" << std::endl;
        else
            std::cout << "ERROR" << std::endl;
    }
    virtual ~I() {}
};

class A : public I { 
};

class B : public I { 
};

int main()
{
    A a;
    a.fSpecific(a);
    B b;
    b.fSpecific(a);
    b.fSpecific((I&)a);

    return 0;
}

不过也有一些问题:

  • 多重继承
  • 对象需要动态转换(这就是我添加虚拟接口的原因)
  • 铸造I也有效。

推荐阅读