go - 是否可以在 C/C++ 中模仿 Go 界面?

标签 go

在 Go 中,如果类型具有接口(interface)定义的所有方法,那么它可以分配给该接口(interface)变量,而无需显式继承它。

是否可以在 C/C++ 中模仿此功能?

最佳答案

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

#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));
}

关于go - 是否可以在 C/C++ 中模仿 Go 界面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8970157/

相关文章:

macos - MacOS 的 Go 1.7 版本错误

google-app-engine - GAE 中 func init() 的第二次执行

sql - 在 Go 中初始化和保留准备好的语句的推荐方法是什么?

go - LiteIDE x14 是否有效?

go - 无法在vscode中自动安装go扩展

go - golang中如何生成多个uuid和md5文件

go - 如何理解这个错误? “unsupported destination, should be slice or struct”

go - 如何调试“语法错误:{之前出现意外的分号或换行符”?

http - 如何获取 http 重定向状态码

sorting - 如何从 Golang 中的 map 中提取 x 个 top int 值?