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.
To merge two interfaces with TypeScript, we can use extends to extend multiple interfaces. to create the IFooBar that extends IFoo and IBar . This means IFooBar has all the members from both interfaces inside.
For the purposes of this article, “declaration merging” means that the compiler merges two separate declarations declared with the same name into a single definition. This merged definition has the features of both of the original declarations.
An interface can be extended by other interfaces. In other words, an interface can inherit from other interface. Typescript allows an interface to inherit from multiple interfaces. Use the extends keyword to implement inheritance among interfaces.
The typescript type supports only the data types and not the use of an object. The typescript interface supports the use of the object.
You can do this in Java:
public <I extends IF1 & IF2> void methodName(I i){
....
}
This way you force I to implement your two interfaces, otherwise it won't even compile.
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 of 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.");
...
}
If T
(a derived class
) is not implementing IF1
and IF2
, then the assertion will fail at compile time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With