Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to mimic Go interface in C/C++?

Tags:

go

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++?

like image 751
alice Avatar asked Jan 23 '12 10:01

alice


1 Answers

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));
}
like image 93
SteveMcQwark Avatar answered Nov 18 '22 08:11

SteveMcQwark