是否有可能在C/C++中模仿Go接口?

ali*_*ice 6 go

在Go中,如果类型具有接口定义的所有方法,则可以将其分配给该接口变量,而不显式继承该接口变量.

是否有可能在C/C++中模仿这个功能?

Ste*_*ark 7

是的。您可以使用纯抽象类,并使用模板类来包装“实现”抽象类的类型,以便它们扩展抽象类。这是一个准系统示例:

#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));
}
Run Code Online (Sandbox Code Playgroud)