合并接口,但不合并
Merging interfaces, without merging
我在想,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
)没有实现IF1
和IF2
,那么断言将在编译时失败。
在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) {
}
为什么要把事情复杂化?
相关文章:
- 使用C++程序合并排序没有得到正确的输出
- C++核心准则 C35 对于接口类"A base class destructor should be either public and virtual, or protected and nonv
- Visual C++GC接口如何启用它以及要包含哪个库
- Windows.h与GLFW.h的接口
- 用于合并排序的合并函数
- 当字段可以为null时,如何使用C++接口在Avro中写入数据
- 在声明中合并两个常量"std::set"(不是在运行时)
- 提供与TMP和SFINAE的通用接口
- 为重写std::exception的库生成swig接口时出错
- 内联如何影响模块接口中的成员函数
- 如何将一个数组值合并为一个整数c++
- 如何将不同的可执行文件合并到一个窗口框架中进行编码?像浏览器一样
- 将向量的 N 段合并到位C++
- COM 接口 c# 封送数组数组
- 如何在 SCIP C++ 接口中获取 MILP 约束矩阵中的系数值
- 重载 -> shared_ptr 个实例中的箭头运算符<interface>,接口中没有纯虚拟析构函数
- 在C++中合并两个库
- 如何绑定 C++ gRPC 客户端的网络接口
- 合并接口,但不合并
- 如何合并一个pImpl接口,同时也允许WndProc与之交互