Is it possible to simulate the Go interface in C / C ++?

In Go, if a type has all the methods defined by an interface, then it can be assigned to this interface variable without explicit inheritance from it.

Is it possible to simulate this function in C / C ++?

+6
source share
4 answers

Yes. You can use a pure abstract class and use the template class to transfer the "implementation" types of the abstract class to extend the abstract class. Here is an example with barebones:

#include <iostream> // Interface type used in function signatures. class Iface { public: virtual int method() const = 0; }; // Template wrapper for types implementing Iface template <typename T> class IfaceT: public Iface { public: explicit IfaceT(T const t):_t(t) {} virtual int method() const { return _t.method(); } private: T const _t; }; // Type implementing Iface class Impl { public: Impl(int x): _x(x) {} int method() const { return _x; } private: int _x; }; // Method accepting Iface parameter void printIface(Iface const &i) { std::cout << i.method() << std::endl; } int main() { printIface(IfaceT<Impl>(5)); } 
+3
source

Oh sure.

In fact, the code that processes the interfaces at runtime is written in C. http://code.google.com/p/go/source/browse/src/pkg/runtime/iface.c

+3
source

I suggest that some approximate equivalence may be feasible with GObject .

0
source

I took a hit in C ++. I ended up with something that works, but it's a macrocycle: https://github.com/wkaras/c-plus-plus-misc/tree/master/IFACE . An interface is two pointers, one for object data elements, and the other the equivalent of a virtual table (a structure of pointers to thunk functions that invoke member functions). These tables (unfortunately) are generated at runtime. Converting from an interface to a sub-interface requires a search in order of unordered_map, so on average this is O (1) complexity. Compared to converting a pointer of a derived class / reference to one to the base class, which is O (1) the worst.

It is not very useful, but it shows that interfaces can be (purely) added in C ++ with relatively little effort. There are times when interfaces are better than OO inheritance, and a cow is good from the barn, as it tries to keep C ++ small.

0
source

Source: https://habr.com/ru/post/906647/


All Articles