合并接口,不合并

问题描述 投票:0回答:6

我在想,C++或者Java有没有办法做这样的事情

Interface IF1{
    ....
};

Interface IF2{
    ....
};


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

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

java c++ type-systems
6个回答
28
投票

您可以在 Java 中执行此操作:

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

....

}

这样,你就强制

I
实现你的两个接口,否则它甚至无法编译。


11
投票

在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
)未实现
IF1
IF2
,则断言将在编译时失败。


3
投票

在 C++ 中你可以做类似的事情:

template <typename T>
void f(T &o)
{
    IF1 &i1 = o;
    IF2 &i2 = o;

    //function body
}

需要带有接口指针的行以确保 T 实现两个接口(如果不是,将导致编译器错误)。


2
投票

使用 boost 库(type_traitsenable_ifand_),你可以做一些非常复杂的事情。

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)
{
  // ...
}

我的代码中可能存在一些怪癖,但你明白了。


1
投票

在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){

}

但是我发现这很令人困惑。如果一个对象需要实现两个不同的接口,我更喜欢第三个。恕我直言,它更干净。


1
投票

有什么问题:

interface IF1IF2 extends IF1, IF2 {}

void f(IF1IF2 o) {
}

为什么要把事情复杂化?

© www.soinside.com 2019 - 2024. All rights reserved.