合并接口,但不合并

Merging interfaces, without merging

本文关键字:合并 接口      更新时间:2023-10-16

我在想,c++或Java有办法做这样的事情吗

Interface IF1{
    ....
};
Interface IF2{
    ....
};

function f(Object o : Implements IF1, IF2){
    ...
}

意味着允许你要求接口实现的类型系统。

您可以在Java中这样做:

public <I extends IF1 & IF2> void methodName(I i){
....
}

这样你就强制I实现了你的两个接口,否则它甚至不会编译。

在c++中我们可以使用std::is_base_of<IF1, Derived>。这必须与实际的派生类型和基类型一起使用,并且在tempalte s的帮助下很容易使用。

template<typename T>
void f (T obj)
{
  static_assert(is_base_of<IF1,T>::value && is_base_of<IF2,T>::value,
  "Error: Not implementing proper interfaces.");
  ...
}

如果T(衍生的class)没有实现IF1IF2,那么断言将在编译时失败。

在c++中你可以这样做:

template <typename T>
void f(T &o)
{
    IF1 &i1 = o;
    IF2 &i2 = o;
    //function body
}
需要带有接口指针的

行来确保T实现这两个接口(如果不这样做会导致编译器错误)。

使用boost库(type_traits, enable_if和_),您可以做一些非常复杂的事情。

template <typename T>
typename boost::enable_if<           // Check whether
    boost::mpl::and_<                // Both of the following conditions are met
        boost::is_base_of<IF1, T>,   // T derives from IF1
        boost::is_base_of<IF2, T>    // T derives from IF2
        >
    >
>::type
function(T& t)
{
  // ...
}

在我的代码中可能会有一些奇怪的地方,但是你明白了。

在java中没有这样的东西,我会添加第三个元素来实现这两个接口,并将其用作参数。这对我来说很有意义,因为第三个对象既不是IF1也不是IF2,只是IF3。

interface a {
  int foo();
}

interface b {
  long foo2();
}
interface c extends a, b {
  long daaa();
}
public class TestInterface {
  void someMethod (c theThird) {
    return;
  }
}

这对我来说是有意义的。

编辑:没有意识到

public <I extends a & b> void methodName(I i){
}

然而,我发现它令人困惑。如果一个对象需要实现两个不同的接口,我更喜欢有第三个接口。我觉得这样更干净。

怎么了

interface IF1IF2 extends IF1, IF2 {}
void f(IF1IF2 o) {
}

为什么要把事情复杂化?