合并接口,不合并
我在想,C++ 或 Java 是否有办法做这样的事情,这
Interface IF1{
....
};
Interface IF2{
....
};
function f(Object o : Implements IF1, IF2){
...
}
意味着类型系统允许您要求实现接口。
I was thinking, does C++ or Java have a way to do something like this
Interface IF1{
....
};
Interface IF2{
....
};
function f(Object o : Implements IF1, IF2){
...
}
meaning a typesystem that allows you to require implementation of interfaces.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以在 Java 中执行此操作:
这样,您可以强制
I
实现您的两个接口,否则它甚至无法编译。You can do this in Java:
This way, you force
I
to implement your two interfaces, otherwise it won't even compile.在 C++ 中,我们可以使用 std::is_base_of。这必须与实际的派生类型和基类型一起使用,并且在 tempalte 的帮助下将很容易使用。
如果
T
(派生类
)未实现IF1
和IF2
,则断言将在编译时失败。In C++, we can use
std::is_base_of<IF1, Derived>
. This has to be used with the actual derived and base type and will be easy to use with the help oftempalte
s.If
T
(a derivedclass
) is not implementingIF1
andIF2
, then the assertion will fail at compile time.在 C++ 中,你可以这样做:
需要带有接口指针的行来确保 T 实现两个接口(如果不是,则会导致编译器错误)。
in C++ you can do something like that:
lines with interface pointer are needed to ensure that T implements both interfaces (it will cause compiler error if it is not).
使用 boost 库 (type_traits, < a href="http://www.boost.org/doc/libs/1_47_0/libs/utility/enable_if.html" rel="nofollow">enable_if, and_),你可以做一些相当复杂的事情。
我的代码中可能存在一些怪癖,但您明白了。
Using boost libraries (type_traits, enable_if, and_), you can do something quite elaborate.
There may be a few quirks here and there in my code, but you get the idea.
在java中没有这样的东西,我会添加第三个元素来实现这两个接口并将其用作参数。这对我来说非常有意义,因为第三个对象既不是 IF1 也不是 IF2,而只是 IF3。
这对我来说很有意义。
编辑:
不知道
但是我发现它令人困惑。如果一个对象需要实现两个不同的接口,我更喜欢第三个。恕我直言,它更干净。
In java there's nothing like this, I would add a third element implementing the two interfaces and use it as a parameter. And this will makes perfect sense to me, because the third object is neither an IF1 nor an IF2, is just an IF3.
this makes sense to me.
EDIT:
Wasn't aware of
However I found it confusing. If an object needs to implement two different Interfaces I prefer to have a third one. IMHO it's cleaner.
有什么问题:
为什么要把事情复杂化?
What's wrong with:
Why overcomplicate things?