In Go, if the type has all the methods that the interface defined then it can be assigned to that interface variable without explicitly inheriting from it.
Is it possible to mimic this feature in C/C++?
Yes. You can use a pure abstract class, and use a template class to wrap types "implementing" the abstract class so that they extend the abstract class. Here's a barebones example:
#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));
}
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