Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging interfaces, without merging

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.

like image 798
Martin Kristiansen Avatar asked Oct 25 '11 08:10

Martin Kristiansen


People also ask

How do I merge two TS 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.

What is declaration merging?

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.

Can an interface extend another interface typescript?

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.

What is the difference between interface and type in typescript?

The typescript type supports only the data types and not the use of an object. The typescript interface supports the use of the object.


2 Answers

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.

like image 193
Francisco Paulo Avatar answered Sep 21 '22 16:09

Francisco Paulo


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 tempaltes.

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.

like image 40
iammilind Avatar answered Sep 21 '22 16:09

iammilind